<?php
/**
 * Created by PhpStorm.
 * User: daimingkang
 * Date: 2018/9/6
 * Time: 下午7:17
 */

namespace App\Api\Controllers\DevicePay;

use App\Api\Controllers\Config\PayWaysController;
use App\Api\Controllers\Merchant\OrderController;
use App\Api\Controllers\Merchant\PayBaseController;
use App\Models\Device;
use App\Models\Merchant;
use App\Models\MerchantStore;
use App\Models\MqttConfig;
use App\Models\Order;
use App\Models\RefundOrder;
use App\Models\Store;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;


/**扫码设备支付接口
 * Class CanyinController
 * @package App\Api\Controllers\DevicePay
 */
class CanyinController extends BaseController
{


    private $deviceKey = "a6b5c7994c48d525e2980855416bb23c08bb3b42";

    /**首次登陆
     * @param Request $request
     * @return string
     */
    public function canyinlogin(Request $request)
    {
        $error = '<dm ok="0" server="http://pay.zgjindoufu.com"/>';
        $device_id = $request->get("device_id");
        /*$local_sign = sha1($this->deviceKey);
        $sign = $request->get("sign");

        if ($sign != $local_sign) {
            return $error;
        }*/
        $Device = Device::where('device_no', $device_id)->first();
        if (!$Device) {
            return $error;
        } else {
            return '<dm ok="1" server="http://pay.zgjindoufu.com"/>';
        }
    }

    /**二级登陆
     * @param Request $request
     * @return string
     */

    public function canyinlogin2(Request $request)
    {

        $device_id = $request->get('device_id');  //机具ID号
        $data = $request->get('data');  //数据 <pay_list pagesize="8" pageindex="1" paytype="207,208" paystate="1,0,2" payover="1,0" />
        // file_put_contents('rel.txt', date('H:i:s') . $data . PHP_EOL, FILE_APPEND);
        // file_put_contents('b534346.log',var_export($data,true)."\r\n",FILE_APPEND);
        $error = '<dm ok="0" server="http://pay.zgjindoufu.com"/>';
        if (!empty($data) && (strpos($data, 'handover') || strpos($data, 'pageindex') || strpos($data, 'pay_listdetail') || strpos($data, 'device_check'))) {
            if (strpos($data, 'handover')) {
                $this->handover($request);
                die();
            }elseif (strpos($data, 'pay_listdetail')) {
                $detail = $this->list_detail($request);
                return $detail;
                die();
            }elseif (strpos($data, 'device_check')) {
                $detail = $this->device_check($request);
                return $detail;
                die();
            } else {
                $this->getlist($request);
                die();
            }
        }
        /*$local_sign = sha1($this->deviceKey);
        $sign = $request->get("sign");

        if ($sign != $local_sign) {
            return $error;
        }*/
        $Device = Device::where('device_no', $device_id)->first();
        if (!$Device) {
            return $error;
        } else {
            /*return '<app ok="1" client_id="537456" device_id="' . $device_id . '" refund_timelimit="0" client_name="' . $Device->store_name . '" payremind_template="\x1b\x40 \x1c\x26 \x1b\x74\x00 \x1D\x21\x11支付凭证 \x1D\x21\x00 商户名称：{company} 设备编号：{device_id} 凭 证 号：{id} 订 单 号：{no} ------------------------------- 支付方式：{paymode} 支付时间：{paytime} 消费金额：\x1D\x21\x11￥{total} \x1b\x40------------------------------- 客户签字： \x0d\x0a ------------------------------- \x1b\x40 \x0d\x0a \x0d\x0a \x1B\x69" payremind_template_popup="时间:{paytime} 单号:{no} 桌号:{tableno} 金额:{total}" qrcode_template="\r\n \x1b\x7b\x01\x1b\x61\x01△ △ △ △ △ △ △ △ △ △\x1b\x7b\x00 \x1b\x40 \x1b\x33\x10{qrcode_logo}\x1b\x40 \x1b\x61\x01感谢您的光临 \x1b\x40 账单总额:\x1d\x21\x11￥{total} \x1b\x40\x1b\x33\x10 {qrcode} \x1b\x40\x1b\x61\x01微信扫一扫，支付享抢优惠 \x1b\x40 ▲ \x1d\x21\x11 立减 5 元 \x1d\x21\x00 ▲\r\n \x1b\x61\x01-------------------------------- \x1b\x40 账单编号:{no} 就餐桌号:{table} 消费时间:{time}" qrcode_logo="201503/31002052/logo150.png" qrcode_image="201503/31002052/wx72.png" redpack_template="" micropay_total_regex="" micropay_timeout="15000" micropay_query_timeout="5000" license_micropay="1" license_printer="1" license_com="1" license_network="1" license_wxpayremind="1" handover_module="o2o_handover" oem_name="yhkj" oem_ver="14" oem_res_ver="2" wxpayremind_print_count="1" splash_image="/o2o_7000/download.7004.php?file=/o2o_7000/splash.png">
  <dm_code type="207" code="o2o_dm_code_wxpayyihoupay_wxpay" name="微信" pay_type="2" pay_name="微信" coderegex="^1[0-5]\d{16}$" cancelregex="^dm\d+$|^wxscan20[0-9]{2}[01]{1}[0-9]{1}[0-3]{1}[0-9]{1}\d{15}$|^[A-Za-z]{8}20[0-9]{2}[01]{1}[0-9]{1}[0-3]{1}[0-9]{1}\d{14}$|^20[0-9]{2}[01]{1}[0-9]{1}[0-3]{1}[0-9]{1}\d{12}$|^5\d{8}$|^11212120[0-9]{2}[01]{1}[0-9]{1}[0-3]{1}[0-9]{1}\d{12}$" undiscounted="0" openregex="^1[0-5]\d{16}$" btnpay_text="微信收银" btnpay_background="#ff09BB07" btnpay_border="#ff07A705" btnpay_clickbackground="#ff07A705" btnpay_focus="#ff20CD1E" btnpay_foreground="#ffffffff" btnpay_logo="/o2o_dm_code_wxpayyihoupay_wxpay/logo_btn.png" pay_logo="/o2o_dm_code_wxpayyihoupay_wxpay/logo.png" /> 
  <dm_code type="208" code="o2o_dm_code_wxpayyihoupay_alipay" name="支付宝" pay_type="3" pay_name="支付宝" coderegex="^2[5-9]\d{14,22}$|^30\d{14,22}$" cancelregex="^dm\d+$|^aliscan20[0-9]{2}[01]{1}[0-9]{1}[0-3]{1}[0-9]{1}\d{15}$|^[A-Za-z]{8}20[0-9]{2}[01]{1}[0-9]{1}[0-3]{1}[0-9]{1}\d{14}$|^20[0-9]{2}[01]{1}[0-9]{1}[0-3]{1}[0-9]{1}\d{12}$|^5\d{8}$|^11212120[0-9]{2}[01]{1}[0-9]{1}[0-3]{1}[0-9]{1}\d{12}$" undiscounted="0" openregex="^2[5-9]\d{14,22}$|^30\d{14,22}$" btnpay_text="支付宝收银" btnpay_background="#ff00A0E9" btnpay_border="#ff0EA6EB" btnpay_clickbackground="#ff0EA6EB" btnpay_focus="#ff30BFFF" btnpay_foreground="#ffffffff" btnpay_logo="/o2o_dm_code_wxpayyihoupay_alipay/logo_btn.png" pay_logo="/o2o_dm_code_wxpayyihoupay_alipay/logo.png" /> 
  <files splash="/o2o_7000/splash.png" /> 
- <mqtt_config>
- <![CDATA[ QiLAWyLg+Oea24QHxLJF43gY+0ZOSG34hBPwMIbtZJd7RJyAGhlXQ/DzlY8hzLRpm2Z2h92QRSRGNpPx2Ef6bIpDbeD4MUxlF6l/pbFtFdrL6fqIy3rs+OzspONYUOv714/FwkPoLtWon3JMwtCIYsRDdxK9NwE+rka+VJqg4RHwks4OANSiFfmyly3nfX00xcpgsU6itlKt3jpnuUd7NxqKYdIyWy4T22mf6gvvERU/y5NoT2HQF3T+o06EZtSLVXfM3MrDG8EjOUahudoFU//KQEjpee9o83rL+T2LuCDKakC6f7oo7gIxXew5EEJnw3e5Icqajq6HiFxxwVk2jQU5RPQ0+YZ7HakXPtEnFTsF8F7RdaBNCsl9Kz2/i8+FiJ0EBxKfGwv6SLyn1FVnpDAZDLVy8C02zwrU8pTleTcE/oOwluXPVSPFznashPT4PlCkGfWu+grGWUBIUVQ93JVTQWwyzWH9pIteu7i1ue+yDHNPBpCzywUZ0wPsO8feoDnQWi2Qz9ELRR4CfF6xwnXFD5A69AJj7wo74aNeCpLm+Sa2sgPMBFsPqQyuS8VgoScf9uS0Qd2/qFYPvshdRQ==
  ]]> 
  </mqtt_config>
  </app>';*/
            $info = '<app ok="1" client_id="537937" device_id="' . $device_id . '" refund_timelimit="0" client_name="' . $Device->store_name . '-' . $Device->store_id . ' - ' . $Device->merchant_name . '-' . $Device->merchant_id . '" payremind_template="\x1b\x40 \x1c\x26 \x1b\x74\x00 \x1D\x21\x11支付凭证 \x1D\x21\x00 商户名称：{company} 设备编号：{device_id} 凭 证 号：{id} 订 单 号：{no} ------------------------------- 支付方式：{paymode} 支付时间：{paytime} 消费金额：\x1D\x21\x11￥{total} \x1b\x40------------------------------- 客户签字： \x0d\x0a ------------------------------- \x1b\x40 \x0d\x0a \x0d\x0a \x1B\x69" payremind_template_popup="时间:{paytime} 单号:{no} 桌号:{tableno} 金额:{total}" qrcode_template="\r\n \x1b\x7b\x01\x1b\x61\x01△ △ △ △ △ △ △ △ △ △\x1b\x7b\x00 \x1b\x40 \x1b\x33\x10{qrcode_logo}\x1b\x40 \x1b\x61\x01感谢您的光临 \x1b\x40 账单总额:\x1d\x21\x11￥{total} \x1b\x40\x1b\x33\x10 {qrcode} \x1b\x40\x1b\x61\x01微信扫一扫，支付享抢优惠 \x1b\x40 ▲ \x1d\x21\x11 立减 5 元 \x1d\x21\x00 ▲\r\n \x1b\x61\x01-------------------------------- \x1b\x40 账单编号:{no} 就餐桌号:{table} 消费时间:{time}" qrcode_logo="201503/31002052/logo150.png" qrcode_image="201503/31002052/wx72.png" redpack_template="" micropay_total_regex="" micropay_timeout="9000" micropay_query_timeout="3000" license_micropay="1" license_printer="1" license_com="1" license_network="1" license_wxpayremind="1" handover_module="o2o_handover" oem_name="huiWangcai" oem_ver="57" oem_res_ver="4" wxpayremind_print_count="1" splash_image="/o2o_7000/download.7004.php?file=/o2o_7000/splash.png">
  <dm_code type="293" code="o2o_dm_code_wxpayhsty_unpay" name="银联" pay_type="4" pay_name="银联云闪付" coderegex="^62\d{16,17}$" cancelregex="^dm\d+$|^\d{12}20\d{16}$" undiscounted="0" openregex="^62\d{16,17}$" btnpay_text="银联收银" btnpay_background="#ff069AB2" btnpay_border="#ff06869B" btnpay_clickbackground="#ff06869B" btnpay_focus="#ff12AFC9" btnpay_foreground="#ffffffff" btnpay_logo="/o2o_dm_code_wxpayhsty_unpay/logo_btn.png" pay_logo="/o2o_dm_code_wxpayhsty_unpay/logo.png" /> 
  <dm_code type="291" code="o2o_dm_code_wxpayhsty_wxpay" name="微信" pay_type="2" pay_name="微信" coderegex="^1[0-5]\d{16}$" cancelregex="^dm\d+$|^\d{12}20\d{16}$" undiscounted="0" openregex="^1[0-5]\d{16}$" btnpay_text="微信收银" btnpay_background="#ff09BB07" btnpay_border="#ff07A705" btnpay_clickbackground="#ff07A705" btnpay_focus="#ff20CD1E" btnpay_foreground="#ffffffff" btnpay_logo="/o2o_dm_code_wxpayhsty_wxpay/logo_btn.png" pay_logo="/o2o_dm_code_wxpayhsty_wxpay/logo.png" /> 
  <dm_code type="292" code="o2o_dm_code_wxpayhsty_alipay" name="支付宝" pay_type="3" pay_name="支付宝" coderegex="^2[5-9]\d{14,22}$|^30\d{14,22}$" cancelregex="^dm\d+$|^\d{12}20\d{16}$" undiscounted="0" openregex="^2[5-9]\d{14,22}$|^30\d{14,22}$" btnpay_text="支付宝收银" btnpay_background="#ff00A0E9" btnpay_border="#ff0EA6EB" btnpay_clickbackground="#ff0EA6EB" btnpay_focus="#ff30BFFF" btnpay_foreground="#ffffffff" btnpay_logo="/o2o_dm_code_wxpayhsty_alipay/logo_btn.png" pay_logo="/o2o_dm_code_wxpayhsty_alipay/logo.png" /> 
  <files splash="/o2o_7000/splash.png" /> 
- <mqtt_config>
- <![CDATA[ QiLAWyLg+Oea24QHxLJF43gY+0ZOSG34hBPwMIbtZJd7RJyAGhlXQ/DzlY8hzLRpm2Z2h92QRSRGNpPx2Ef6bIpDbeD4MUxlF6l/pbFtFdrL6fqIy3rs+OzspONYUOv714/FwkPoLtWon3JMwtCIYsRDdxK9NwE+rka+VJqg4RHwks4OANSiFfmyly3nfX00xcpgsU6itlKt3jpnuUd7NxqKYdIyWy4T22mf6gvvERU/y5NoT2HQF3T+o06EZtSLVXfM3MrDG8EjOUahudoFU//KQEjpee9o83rL+T2LuCDKakC6f7oo7gIxXew5EEJnw3e5Icqajq6HiFxxwVk2jQU5RPQ0+YZ7HakXPtEnFTsF8F7RdaBNCsl9Kz2/i8+FiJ0EBxKfGwv6SLyn1FVnpDAZDLVy8C02zwrU8pTleTcE/oOwluXPVSPFznashPT4PlCkGfWu+grGWUBIUVQ93JVTQWwyzWH9pIteu7i1ue+yDHNPBpCzywUZ0wPsO8feoDnQWi2Qz9ELRR4CfF6xwnXFD5A69AJj7wo74aNeCpLm+Sa2sgPMBFsPqQyuS8VgoScf9uS0Qd2/qFYPvshdRQ==
  ]]> 
  </mqtt_config>
  </app>';
            return $info;
        }
    }


    public function canyinpay(Request $request){
        $data33 = $request->getContent();
        $out_trade_no = $request->get('Run_number');
        $action = $request->get('action'); //判断支付还是查询 micropay 支付  否而为查询
        $auth_code = $request->get('authcode');
        $device_id = $request->get('device_id');  //机具ID号
        $total = $request->get('total');  //支付金额  单位：元
        $refund_cx = $request->get('data');  //退款查询
        if (!empty($refund_cx) && strpos($refund_cx, "pay_refundquery")) {
            sleep(5);
            $info = $this->refund_cx($device_id, $refund_cx);
            return $info;
            die();
        }

        if ($action == 'micropay') {
            //支付
            
            $data = array();
            $data['total_amount'] = $total;
            $data['code'] = $auth_code;
            $data['device_id'] = $device_id;
            $data['device_type'] = 'y_plugin_1';
            $data['qwx_no'] = $out_trade_no;
            
            
            $result = $this->scan_pay($data);
            
            $store = DB::table('stores')->where([ 'store_id' => $result['store_id'] ])->first(); // 门店
            $device = DB::table('devices')->where([ 'device_no' => $data['device_id'] ])->first(); // 
            
            if ($result['return_code'] == 'FALL') {
                $info = '<dm ok="0" info="支付失败【订单支付失败】" remark="" openid="" no="" />';
            } else {
                if ($result['result_code'] == 'USERPAYING') {
                    $info = '<dm ok="-1" info="用户支付中【用户正在支付】" dm_id="' . $result["out_trade_no"] . '" remark="" openid="" pay_id="" no=""/>';
                } else if ($result['result_code'] == 'SUCCESS') {
                    
                    $pay_type = '';
                    if ($result['ways_source'] == 'alipay') {
                        $pay_type = 'pay.alipay.micropay';
                        $pay_type_show = '支付宝';
                    } elseif ($result['ways_source'] == 'weixin') {
                        $pay_type = 'pay.weixin.micropay';
                        $pay_type_show = '微信';
                    } else {
                        $pay_type_show = '银联';
                    }
                    
                    
                    
                    // \x1b\x61\x01皖付通服务热线：400-087-0987

                    $info = '<dm ok="1" info="支付成功" dm_id="' . $result["out_trade_no"] . '" total="' . $total . '" pay_type="208" pay_time="' . $result["pay_time"] . '" pay_id="' . $result["out_transaction_id"] . '" openid="" no="" type_id="3">
<ok>1</ok>
        <paylist>
            <pay>
                <id>' . $result["out_trade_no"] . '</id>
                <device_id>' . $device_id . '</device_id>
                <no></no>
                <tabno></tabno>
                <company>淮阴区益鲜超市-238</company>
                <opentime>' . $result["pay_time"] . '</opentime>
                <paymode>' . $pay_type_show . '</paymode>
                <user></user>
                <total_fee>' . $total . '</total_fee>
                <time>' . $result["pay_time"] . '</time>
                <printinfo>\x1b\x40\x1c\x26
\x1b\x74\x00
\x1b\x61\x01\x1D\x21\x10付款回执
\x1b\x40商户名称：' . $store->store_name . '
交易时间：' . $result['pay_time'] . '
DM 单 号：' . $data['qwx_no'] . '
订 单 号：' . $result['out_trade_no'] . '
付款方式：' . $pay_type_show . '
设备信息：' . $device->merchant_name . '-'. $device->merchant_id . '(' . $data['device_id'] . ')
流 水 号：' . $result['out_trade_no'] . '
-------------------------------
订单总额：' . $result['total_amount'] . '
\x1b\x40-------------------------------
签名：
\x0d\x0a
-------------------------------
\x1b\x61\x01Powerd by : 皖付通 . 微收银
\x1b\x40
\x0d\x0a
\x1B\x69</printinfo>
            </pay>
        </paylist>
        <Canvas Height="200" Width="246" Margin="10,16,10,64" VerticalAlignment="Top" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Image HorizontalAlignment="Left" Height="48" VerticalAlignment="Top" Width="48" Source="Resources/popup_alipay.png" Canvas.Left="28" Canvas.Top="6" Stretch="None" />
    <TextBlock Canvas.Left="83" TextWrapping="Wrap" Foreground="#FF6D6D6D" FontSize="21" Canvas.Top="23" Text="' . $pay_type_show . '" />
    <TextBlock Canvas.Left="36" TextWrapping="Wrap" Foreground="#FF6D6D6D" FontSize="16" Canvas.Top="70" Text="单号: ' . $result["out_trade_no"] . '" />
    <TextBlock Canvas.Left="36" TextWrapping="Wrap" Foreground="#FF6D6D6D" FontSize="16" Canvas.Top="100" Text="时间: ' . $result["pay_time"] . '" />
    <TextBlock Canvas.Left="36" TextWrapping="Wrap" Foreground="#FFC90202" FontSize="22" Canvas.Top="140" Text="支付金额: ' . $total . '" /></Canvas>
</dm>';
                }

            }
            return $info;
        } elseif ($action == 'refund') {
            //退款
            $data = array();
            $data['device_id'] = $device_id;
            $data['device_type'] = 'y_plugin_1';
            $dm_id = $request->get('dm_id');   //返回的DMID，其实为系统的 out_trade_no;
            $refund_amount = $request->get('refund');   //退款金额


            if (substr($dm_id,0,2)=='dm'){
                $data['out_trade_no'] = str_replace("dm", "", $dm_id);
            }else{
                $data['out_trade_no'] = $dm_id;   //返回的DMID，其实为系统的 out_trade_no;
            }
            $data['refund_amount'] = $refund_amount;

            $result = $this->refund($data);
            // file_put_contents('65464654.log',var_export($result,true)."\r\n",FILE_APPEND);
            // var_export($result);
            // $result['pay_time'] = date("Y-m-d H:i:s");
            $pay_type = '';
            /*if ($result['ways_source'] == 'alipay') {
                $pay_type = 'pay.alipay.micropay';
                $pay_type_show = '支付宝';
            }
            if ($result['ways_source'] == 'weixin') {
                $pay_type = 'pay.weixin.micropay';
                $pay_type_show = '微信';
            }*/

            $info = '<dm ok="0" info="【失败1】" remark="" openid="" no="" />';
            if ($result['return_code'] == 'FALL') {
                $info = '<dm ok="-1" info="' . $result['return_msg'] . '" remark="" openid="" no="" />';
                //$info = '<dm ok="-1" info="'.$result['return_msg'].'" remark="" openid="" no="" />';
                // sleep(3);//等待10秒中，进入查询流程
                // $qdata['out_trade_no'] = $data['out_trade_no'];   //此处为run_number
                // $qdata['device_id'] = $device_id;
                // $qdata['device_type'] = 'y_plugin_1';
                // $result = $this->refund_query($qdata);

//                 if ($result['return_code'] == 'FALL') {
//                     $info = '<dm ok="-1" info="' . $result['return_msg'] . '" remark="" openid="" no="" />';
//                 } else {
//                     $info = '
//                 <dm ok="1" info="退款成功" dm_id="' . $data['out_trade_no'] . '" pay_type="208" pay_time="' . $result['pay_time'] . '" total="' . $result['refund_amount'] . '" pay_id="' . $data['out_trade_no'] . '" no="" type_id="3">
//         <ok>1</ok>
//         <paylist>
//             <pay>
//                 <id>7048734317</id>
//                 <device_id>' . $device_id . '</device_id>
//                 <no></no>
//                 <tabno></tabno>
//                 <company>' . $result['store_name'] . '</company>
//                 <opentime>' . $result['pay_time'] . '</opentime>
//                 <paymode></paymode>
//                 <user></user>
//                 <total_fee>' . $result['refund_amount'] . '</total_fee>
//                 <time>' . $result['pay_time'] . '</time>
//                 <printinfo>\x1b\x40\x1c\x26
// \x1b\x74\x00
// \x1b\x61\x01\x1D\x21\x10退款凭证
// \x1b\x40商户名称：' . $result['store_name'] . '
// DM 单 号：' . $result['out_trade_no'] . '
// 订 单 号：' . $result['out_trade_no'] . '
// 付款方式：' . $result['ways_source_desc'] . '
// 设备信息：' . $result['merchant_name'] . '-(' . $device_id . ')
// 流 水 号：' . $result['trade_no'] . '
// -------------------------------
// 付款时间：' . $result['time_end'] . '
// 支付金额：' . $result['refund_amount'] . '

// 退款时间：' . $result['pay_time'] . '
// 退款金额：\x1D\x21\x01￥-' . $result['refund_amount'] . '
// \x1b\x40-------------------------------
// \x1b\x40-------------------------------
// 客户签字：
// \x0d\x0a
// \x0d\x0a
// \x1B\x69</printinfo>
//             </pay>
//         </paylist>
//         <Canvas Height="215" Width="246" Margin="10,16,10,64" VerticalAlignment="Top" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
//     <Image HorizontalAlignment="Left" Height="48" VerticalAlignment="Top" Width="48" Source="Resources/popup_alipay.png" Canvas.Left="28" Canvas.Top="6" Stretch="None" />
//     <TextBlock Canvas.Left="83" TextWrapping="Wrap" Foreground="#FF6D6D6D" FontSize="21" Canvas.Top="23" Text="" /><TextBlock Canvas.Left="28" TextWrapping="Wrap" Foreground="#FF6D6D6D" FontSize="15" Canvas.Top="65" Text="单号: 7048734317" />
//     <TextBlock Canvas.Left="28" TextWrapping="Wrap" Foreground="#FF6D6D6D" FontSize="15" Canvas.Top="90" Text="付款时间: 2022-06-01 09:31:15" /><TextBlock Canvas.Left="28" TextWrapping="Wrap" Foreground="#FF6D6D6D" FontSize="15" Canvas.Top="115" Text="付款金额: ' . $result['refund_amount'] . '" />
//     <TextBlock Canvas.Left="28" TextWrapping="Wrap" Foreground="#FF6D6D6D" FontSize="15" Canvas.Top="140" Text="退款时间: 2022-06-01 09:32:01" /><TextBlock Canvas.Left="28" TextWrapping="Wrap" Foreground="#FFC90202" FontSize="22" Canvas.Top="165" Text="退款金额：-' . $result['refund_amount'] . '" /></Canvas>
//                 </dm>';
//                 }
            } elseif ($result['return_code'] == 'SUCCESS') {
                $info = '
                <dm ok="1" info="退款成功" dm_id="' . $data['out_trade_no'] . '" pay_type="208" pay_time="' . $result['pay_time'] . '" total="' . $result['refund_amount'] . '" pay_id="' . $data['out_trade_no'] . '" no="" type_id="3">
        <ok>1</ok>
        <paylist>
            <pay>
                <id>7048734317</id>
                <device_id>' . $device_id . '</device_id>
                <no></no>
                <tabno></tabno>
                <company>' . $result['store_name'] . '</company>
                <opentime>' . $result['pay_time'] . '</opentime>
                <paymode></paymode>
                <user></user>
                <total_fee>' . $result['refund_amount'] . '</total_fee>
                <time>' . $result['pay_time'] . '</time>
                <printinfo>\x1b\x40\x1c\x26
\x1b\x74\x00
\x1b\x61\x01\x1D\x21\x10退款凭证
\x1b\x40商户名称：' . $result['store_name'] . '
DM 单 号：' . $result['out_trade_no'] . '
订 单 号：' . $result['out_trade_no'] . '
付款方式：' . $result['ways_source_desc'] . '
设备信息：' . $result['merchant_name'] . '-(' . $device_id . ')
流 水 号：' . $result['trade_no'] . '
-------------------------------
付款时间：' . $result['time_end'] . '
支付金额：' . $result['refund_amount'] . '

退款时间：' . $result['pay_time'] . '
退款金额：\x1D\x21\x01￥-' . $result['refund_amount'] . '
\x1b\x40-------------------------------
\x1b\x40-------------------------------
客户签字：
\x0d\x0a
\x0d\x0a
\x1B\x69</printinfo>
            </pay>
        </paylist>
        <Canvas Height="215" Width="246" Margin="10,16,10,64" VerticalAlignment="Top" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Image HorizontalAlignment="Left" Height="48" VerticalAlignment="Top" Width="48" Source="Resources/popup_alipay.png" Canvas.Left="28" Canvas.Top="6" Stretch="None" />
    <TextBlock Canvas.Left="83" TextWrapping="Wrap" Foreground="#FF6D6D6D" FontSize="21" Canvas.Top="23" Text="" /><TextBlock Canvas.Left="28" TextWrapping="Wrap" Foreground="#FF6D6D6D" FontSize="15" Canvas.Top="65" Text="单号: 7048734317" />
    <TextBlock Canvas.Left="28" TextWrapping="Wrap" Foreground="#FF6D6D6D" FontSize="15" Canvas.Top="90" Text="付款时间: 2022-06-01 09:31:15" /><TextBlock Canvas.Left="28" TextWrapping="Wrap" Foreground="#FF6D6D6D" FontSize="15" Canvas.Top="115" Text="付款金额: ' . $result['refund_amount'] . '" />
    <TextBlock Canvas.Left="28" TextWrapping="Wrap" Foreground="#FF6D6D6D" FontSize="15" Canvas.Top="140" Text="退款时间: 2022-06-01 09:32:01" /><TextBlock Canvas.Left="28" TextWrapping="Wrap" Foreground="#FFC90202" FontSize="22" Canvas.Top="165" Text="退款金额：-' . $result['refund_amount'] . '" /></Canvas>
                </dm>';
            }
            return $info;
        } else {
            //查询
            $out_trade_no = $request->get('dm_id');   //返回的DMID，其实为系统的 out_trade_no
            $data = array();
            $data['out_trade_no'] = $out_trade_no;
            // $isrefund_no = preg_match('/[a-zA-Z]/', $out_trade_no);  //含有字母 本系统内的ID
            // if ($isrefund_no) {
                //支付查询
                $data['out_trade_no'] = $out_trade_no;   //此处为run_number
                $data['device_id'] = $device_id;
                $data['device_type'] = 'y_plugin_1';
                // file_put_contents('youpay.log',var_export($data,true)."\r\n",FILE_APPEND);
                $result = $this->order_query($data);
                if(empty($total)){
                    $total=$result['total_amount'];
                }
                
                $store = DB::table('stores')->where([ 'store_id' => $result['store_id'] ])->first(); // 门店
                $device = DB::table('devices')->where([ 'device_no' => $data['device_id'] ])->first(); // 
                
                if ($result['result_code'] == 'FALL') {
                    $info = '<dm ok="0" info="'.$result['return_msg'].'" remark="" openid="" no="" />';
                } else {
                    if ($result['result_code'] == 'USERPAYING') {
                        $info = '<dm ok="-1" info="用户支付中【用户正在支付】" dm_id="' . $result["out_trade_no"] . '" remark="" openid="" pay_id="" no=""/>';
                    }elseif ($result['result_code'] == 'SUCCESS') {
                        $pay_type = '';
                        if ($result['ways_source'] == 'alipay') {
                            $pay_type = 'pay.alipay.micropay';
                            $pay_type_show = '支付宝';
                        } elseif ($result['ways_source'] == 'weixin') {
                            $pay_type = 'pay.weixin.micropay';
                            $pay_type_show = '微信';
                        } else {
                            $pay_type_show = '银联';
                        }
                        $pay_time = strtotime($result['pay_time']);
                                                // file_put_contents('5745747.log',var_export(666,true)."\r\n",FILE_APPEND);
                        $info = '<dm ok="1" info="支付成功" dm_id="' . $result["out_trade_no"] . '" total="' . $total . '" pay_type="208" pay_time="' . $result["pay_time"] . '" pay_id="' . $result["out_transaction_id"] . '" openid="" no="" type_id="3">
<ok>1</ok>
        <paylist>
            <pay>
                <id>' . $result["out_trade_no"] . '</id>
                <device_id>' . $device_id . '</device_id>
                <no></no>
                <tabno></tabno>
                <company>淮阴区益鲜超市-238</company>
                <opentime>' . $result["pay_time"] . '</opentime>
                <paymode>' . $pay_type_show . '</paymode>
                <user></user>
                <total_fee>' . $total . '</total_fee>
                <time>' . $result["pay_time"] . '</time>
                <printinfo>\x1b\x40\x1c\x26
\x1b\x74\x00
\x1b\x61\x01\x1D\x21\x10付款回执
\x1b\x40商户名称：' . $store->store_name . '
交易时间：' . $result['pay_time'] . '
DM 单 号：' . $result['out_trade_no'] . '
订 单 号：' . $result['out_trade_no'] . '
付款方式：' . $pay_type_show . '
设备信息：' . $device->merchant_name . '-'. $device->merchant_id . '(' . $data['device_id'] . ')
流 水 号：' . $result['out_trade_no'] . '
-------------------------------
订单总额：' . $result['total_amount'] . '
\x1b\x40-------------------------------
签名：
\x0d\x0a
-------------------------------
\x1b\x61\x01QWX服务热线：400-087-0987
\x1b\x61\x01Powerd by : QWX . 微收银
\x1b\x40
\x0d\x0a
\x1B\x69</printinfo>
            </pay>
        </paylist>
        <Canvas Height="200" Width="246" Margin="10,16,10,64" VerticalAlignment="Top" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Image HorizontalAlignment="Left" Height="48" VerticalAlignment="Top" Width="48" Source="Resources/popup_alipay.png" Canvas.Left="28" Canvas.Top="6" Stretch="None" />
    <TextBlock Canvas.Left="83" TextWrapping="Wrap" Foreground="#FF6D6D6D" FontSize="21" Canvas.Top="23" Text="' . $pay_type_show . '" />
    <TextBlock Canvas.Left="36" TextWrapping="Wrap" Foreground="#FF6D6D6D" FontSize="16" Canvas.Top="70" Text="单号: ' . $result["out_trade_no"] . '" />
    <TextBlock Canvas.Left="36" TextWrapping="Wrap" Foreground="#FF6D6D6D" FontSize="16" Canvas.Top="100" Text="时间: ' . $result["pay_time"] . '" />
    <TextBlock Canvas.Left="36" TextWrapping="Wrap" Foreground="#FFC90202" FontSize="22" Canvas.Top="140" Text="支付金额: ' . $total . '" /></Canvas>
</dm>';
// file_put_contents('5745747.log',var_export($info,true)."\r\n",FILE_APPEND);
                    }else{
                         $info = '<dm ok="0" info="'.$result['result_msg'].'" remark="" openid="" no="" />';
                    }
                }
            // }
            return $info;
        }
    }

    /**
     * 退款查询第1步和第3步
     * @param Request $request
     */

    public function refundquery(Request $request)
    {
        $device_id = $request->get('device_id');  //机具ID号
        $other_no_data = $request->get('data');  //数据  <pay_read dm_id="83620220601671013490" />
        if (strpos($other_no_data, "pay_read")) {
            $info = $this->refundquery1($device_id, $other_no_data);
        }
        if (strpos($other_no_data, "pay_refundquery")) {
            sleep(10);
            $info = $this->refund_cx($device_id, $other_no_data);
        }
        return $info;
    }

    /** 第一步查询
     * @param $device_id
     * @param $other_no_data
     * @return string
     */
    public function refundquery1($device_id, $other_no_data)
    {
        //$device_id = $request->get('device_id');  //机具ID号
        // $other_no_data = $request->get('data');  //数据  <pay_read dm_id="83620220601671013490" />
        $other_no_data = str_replace(['<pay_read dm_id="', '" />'], '', $other_no_data);
        // echo '<pre>';
        // print_r($other_no_data);
        // die;
        // if (preg_match('/\d+/', $other_no_data, $arr)) {
        //     $other_no = $arr[0];
        // }
        // $orderids = DB::table('orderids')->Where('other_no', $other_no)->first();
        // if (!$orderids) {
        //     $info = '<dm ok="0" info="订单不存在" remark="" openid="" no="" />';
        //     return $info;
        // } else {
            $out_trade_no = $other_no_data;
        // }

/*
        $data['out_trade_no'] = $out_trade_no;   //此处为run_number
        $data['device_id'] = $device_id;
        $data['device_type'] = 'y_plugin_1';

        $result = $this->order_query($data);*/
      //  var_export($result);

        // $a = array('a', '_', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
        // $b = str_ireplace($a, "", $out_trade_no);
        // $day = substr($b, 0, 8);
        $table = 'orders';
        $orderdata = array();
        // if (Schema::hasTable($table)) {
        //     $orderdata = DB::table($table)->orWhere('out_trade_no', $out_trade_no)
        //         ->orWhere('trade_no', $out_trade_no)
        //         ->first();

        // } else {
            $orderdata = DB::table('orders')->orWhere('out_trade_no', $out_trade_no)
                ->orWhere('trade_no', $out_trade_no)->orWhere('qwx_no', $out_trade_no)
                ->first();
        // }


        if (!$orderdata) {
            $info = '<dm ok="0" info="无此订单" remark="" openid="" no="" />';
        } else {
          //  var_export($orderdata);
            $result=[
                'ways_source' => $orderdata->ways_source,
                'total_amount' => $orderdata->total_amount,
                'pay_amount' => $orderdata->total_amount,
                'pay_time' => $orderdata->pay_time,
                'status' => $orderdata->status,
                'trade_no' => $orderdata->trade_no,
                'refund_time' => $orderdata->updated_at,
                'out_trade_no' => $orderdata->out_trade_no,
                'out_trade_no' => $orderdata->out_trade_no,
            ];
            $pay_type = '';
            if ($result['ways_source'] == 'alipay') {
                $pay_type = 'pay.alipay.micropay';
                $pay_type_show = '支付宝';
            } elseif ($result['ways_source'] == 'weixin') {
                $pay_type = 'pay.weixin.micropay';
                $pay_type_show = '微信';
            } else {
                $pay_type_show = '银联';
            }


            $info = '<pay_read ok="1" dm_id="' . $result["out_trade_no"] . '" total="' . $result["pay_amount"] . '" pay_time="' . $result["pay_time"] . '" pay_typecode="208" pay_typename="' . $pay_type_show . '" pay_id="' . $orderdata->qwx_no . '" staff="" invoice_total="' . $result["pay_amount"] . '" has_refund="0"><xaml>
<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"><TextBlock Text="支付成功" FontSize="12" Foreground="#ff09bb07" Margin="0,50,0,0" HorizontalAlignment="Center" VerticalAlignment="Top"/><WrapPanel Margin="0,68,0,0" HorizontalAlignment="Center" VerticalAlignment="Top">
	        <TextBlock FontSize="20" Foreground="#ff333333" FontFamily="Arial" FontWeight="Bold" Text="￥" VerticalAlignment="Bottom"/><TextBlock FontSize="40" Foreground="#ff151515" FontFamily="Arial" FontWeight="Bold" Text="0." Margin="0,0,0,-4"/><TextBlock FontSize="20" Foreground="#ff151515" FontFamily="Arial" FontWeight="Bold" Text="01" VerticalAlignment="Bottom"/></WrapPanel>
	    <StackPanel Margin="11,123,0,0" Width="289" Height="194" VerticalAlignment="Top"><Grid Height="16">
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="订单号"/>
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="' . $result["out_trade_no"] . '" FontFamily="Arial" HorizontalAlignment="Right"/>
			</Grid>
			<Grid Height="16">
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="收银时间"/>
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="' . $result["pay_time"] . '" FontFamily="Arial" HorizontalAlignment="Right"/>
			</Grid>
			<Grid Height="16">
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="支付方式"/>
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="' . $pay_type_show . '" FontFamily="Arial" HorizontalAlignment="Right"/>
			</Grid><Grid Height="16">
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="流水号"/>
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="' . $orderdata->qwx_no . '" FontFamily="Arial" HorizontalAlignment="Right"/>
			</Grid><Grid Height="16">
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="订单金额"/>
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="' . $result["total_amount"] . '" FontFamily="Arial" HorizontalAlignment="Right"/>
			</Grid><Grid Height="16">
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="实收"/>
				<TextBlock FontSize="12" Foreground="#ff09bb07" VerticalAlignment="Center" Text="' . $result["pay_amount"] . '" FontFamily="Arial" HorizontalAlignment="Right"/>
			</Grid></StackPanel>
		    <TextBlock Text="按方向键滚动查看" Margin="0,315,0,0" FontSize="10" Foreground="#ff999999" HorizontalAlignment="Center" VerticalAlignment="Top"/>
		</Grid></xaml></pay_read>';

        }









      /*  if ($result['return_code'] == 'FALL') {
            $info = '<dm ok="0" info="'.$result['return_msg'].'" remark="" openid="" no="" />';
        } else {
            if ($result['result_code'] == 'USERPAYING') {
                $info = '<dm ok="-1" info="用户支付中【用户正在支付】" dm_id="' . $result["out_trade_no"] . '" remark="" openid="" pay_id="" no=""/>';
            } elseif ($result['result_code'] == 'SUCCESS') {
                $pay_type = '';



                $pay_time = strtotime($result['pay_time']);
                $info = '<pay_read ok="1" dm_id="' . $result["out_trade_no"] . '" total="' . $result["pay_amount"] . '" pay_time="' . $result["pay_time"] . '" pay_typecode="208" pay_typename="' . $pay_type_show . '" pay_id="' . $other_no . '" staff="" invoice_total="' . $result["pay_amount"] . '" has_refund="0"><xaml>
<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"><TextBlock Text="支付成功" FontSize="12" Foreground="#ff09bb07" Margin="0,50,0,0" HorizontalAlignment="Center" VerticalAlignment="Top"/><WrapPanel Margin="0,68,0,0" HorizontalAlignment="Center" VerticalAlignment="Top">
	        <TextBlock FontSize="20" Foreground="#ff333333" FontFamily="Arial" FontWeight="Bold" Text="￥" VerticalAlignment="Bottom"/><TextBlock FontSize="40" Foreground="#ff151515" FontFamily="Arial" FontWeight="Bold" Text="0." Margin="0,0,0,-4"/><TextBlock FontSize="20" Foreground="#ff151515" FontFamily="Arial" FontWeight="Bold" Text="01" VerticalAlignment="Bottom"/></WrapPanel>
	    <StackPanel Margin="11,123,0,0" Width="289" Height="194" VerticalAlignment="Top"><Grid Height="16">
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="订单号"/>
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="' . $result["out_trade_no"] . '" FontFamily="Arial" HorizontalAlignment="Right"/>
			</Grid>
			<Grid Height="16">
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="收银时间"/>
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="' . $result["pay_time"] . '" FontFamily="Arial" HorizontalAlignment="Right"/>
			</Grid>
			<Grid Height="16">
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="支付方式"/>
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="' . $pay_type_show . '" FontFamily="Arial" HorizontalAlignment="Right"/>
			</Grid><Grid Height="16">
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="流水号"/>
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="' . $other_no . '" FontFamily="Arial" HorizontalAlignment="Right"/>
			</Grid><Grid Height="16">
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="订单金额"/>
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="' . $result["total_amount"] . '" FontFamily="Arial" HorizontalAlignment="Right"/>
			</Grid><Grid Height="16">
				<TextBlock FontSize="12" Foreground="#ff333333" VerticalAlignment="Center" Text="实收"/>
				<TextBlock FontSize="12" Foreground="#ff09bb07" VerticalAlignment="Center" Text="' . $result["pay_amount"] . '" FontFamily="Arial" HorizontalAlignment="Right"/>
			</Grid></StackPanel>
		    <TextBlock Text="按方向键滚动查看" Margin="0,315,0,0" FontSize="10" Foreground="#ff999999" HorizontalAlignment="Center" VerticalAlignment="Top"/>
		</Grid></xaml></pay_read>';*/

                /*             $info='<app ok="1" client_id="537456" device_id="{device_id}" refund_timelimit="0" client_name="翼支付测试" payremind_template="\x1b\x40 \x1c\x26 \x1b\x74\x00 \x1D\x21\x11支付凭证 \x1D\x21\x00 商户名称：{company} 设备编号：{device_id} 凭 证 号：{id} 订 单 号：{no} ------------------------------- 支付方式：{paymode} 支付时间：{paytime} 消费金额：\x1D\x21\x11￥{total} \x1b\x40------------------------------- 客户签字： \x0d\x0a ------------------------------- \x1b\x40 \x0d\x0a \x0d\x0a \x1B\x69" payremind_template_popup="时间:{paytime} 单号:{no} 桌号:{tableno} 金额:{total}" qrcode_template="\r\n \x1b\x7b\x01\x1b\x61\x01△ △ △ △ △ △ △ △ △ △\x1b\x7b\x00 \x1b\x40 \x1b\x33\x10{qrcode_logo}\x1b\x40 \x1b\x61\x01感谢您的光临 \x1b\x40 账单总额:\x1d\x21\x11￥{total} \x1b\x40\x1b\x33\x10 {qrcode} \x1b\x40\x1b\x61\x01微信扫一扫，支付享抢优惠 \x1b\x40 ▲ \x1d\x21\x11 立减 5 元 \x1d\x21\x00 ▲\r\n \x1b\x61\x01-------------------------------- \x1b\x40 账单编号:{no} 就餐桌号:{table} 消费时间:{time}" qrcode_logo="201503/31002052/logo150.png" qrcode_image="201503/3100205272.png" redpack_template="" micropay_total_regex="" micropay_timeout="15000" micropay_query_timeout="5000" license_micropay="1" license_printer="1" license_com="1" license_network="1" license_wxpayremind="1" handover_module="o2o_handover" oem_name="yhkj" oem_ver="14" oem_res_ver="2" wxpayremind_print_count="1" splash_image="/o2o_7000/download.7004.php?file=/o2o_7000/splash.png">
                  <dm_code type="207" code="o2o_dm_code_wxpayyihoupay_wxpay" name="微信" pay_type="2" pay_name="微信" coderegex="^1[0-5]\d{16}$" cancelregex="^dm\d+$|^wxscan20[0-9]{2}[01]{1}[0-9]{1}[0-3]{1}[0-9]{1}\d{15}$|^[A-Za-z]{8}20[0-9]{2}[01]{1}[0-9]{1}[0-3]{1}[0-9]{1}\d{14}$|^20[0-9]{2}[01]{1}[0-9]{1}[0-3]{1}[0-9]{1}\d{12}$|^5\d{8}$|^11212120[0-9]{2}[01]{1}[0-9]{1}[0-3]{1}[0-9]{1}\d{12}$" undiscounted="0" openregex="^1[0-5]\d{16}$" btnpay_text="微信收银" btnpay_background="#ff09BB07" btnpay_border="#ff07A705" btnpay_clickbackground="#ff07A705" btnpay_focus="#ff20CD1E" btnpay_foreground="#ffffffff" btnpay_logo="/o2o_dm_code_wxpayyihoupay_wxpay/logo_btn.png" pay_logo="/o2o_dm_code_wxpayyihoupay_wxpay/logo.png" />';*/

        /*            //  $info = str_replace(['{device_id}','{paytime}','{total}','{no}','{time}','{company}','{paymode}'], [$device_id,$result["pay_time"], $result["pay_amount"], $result["out_trade_no"],$result["pay_time"],$pay_type_show,$pay_type_show], $info);

               }
           }

          */
        return $info;

    }

    /**第3步查询
     * @param $device_id
     * @param $other_no_data
     * @return string
     */
    public function refund_cx($device_id, $other_no_data)
    {
        //$device_id = $request->get('device_id');  //机具ID号
        // $other_no_data = $request->get('data');  //数据  <pay_read dm_id="83620220601671013490" />
        //   var_export($other_no_data);
        $other_no = str_replace(['<pay_refundquery dm_id="', '" />'], '', $other_no_data);
        /*if (preg_match('/\d+/', $other_no_data, $arr)) {
            $other_no = $arr[0];
        }
        var_export($other_no);*/
        /* $orderids = DB::table('orderids')->Where('out_trade_no', $other_no)->first();
         if (!$orderids) {
             $info = '<dm ok="0" info="订单不存在" remark="" openid="" no="" />';
             return $info;
         } else {
             $out_trade_no = $orderids->out_trade_no;
         }*/


        $data['out_trade_no'] = $other_no;   //此处为run_number
        $data['device_id'] = $device_id;
        $data['device_type'] = 'y_plugin_1';

        $result = $this->refund_query($data);
        //   var_export($result);


        if ($result['return_code'] == 'FALL') {
            $info = '<dm ok="0" info="未找到" remark="" openid="" no="" />';
        } else {
            if ($result['result_code'] == 'SUCCESS') {
                $pay_type = '';
                if ($result['ways_source'] == 'alipay') {
                    $pay_type = 'pay.alipay.micropay';
                    $pay_type_show = '支付宝';
                } elseif ($result['ways_source'] == 'weixin') {
                    $pay_type = 'pay.weixin.micropay';
                    $pay_type_show = '微信';
                } else {
                    $pay_type_show = '银联';
                }

                $info = '<pay_refundquery ok="1"><xaml><Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
            <WrapPanel Margin="0,84,0,0" HorizontalAlignment="Center" VerticalAlignment="Top">
                <TextBlock FontSize="20" FontWeight="Bold" Foreground="#ff151515" Text="￥" VerticalAlignment="Bottom"/>
                <TextBlock FontSize="40" FontWeight="Bold" Foreground="#ff151515" Text="' . $result["refund_amount"] . '" Margin="0,0,0,-5" FontFamily="Arial"/>
                <TextBlock FontSize="20" FontWeight="Bold" Foreground="#ff151515" Text="元" VerticalAlignment="Bottom" FontFamily="Arial"/>
            </WrapPanel>
            <StackPanel Margin="0,142,0,0" HorizontalAlignment="Center" VerticalAlignment="Top" Width="286" Height="220">   
                 <TextBlock Text="退款记录" FontSize="12" Foreground="#ff333333" HorizontalAlignment="Center"/><Grid Height="16">
                    <TextBlock Foreground="#ff666666" Text="' . $result["pay_time"] . '"/>
                    <TextBlock Foreground="#ff666666" Text="-' . $result["refund_amount"] . '" HorizontalAlignment="Right"/>
                </Grid>        <Grid Height="16">
                    <TextBlock Text="退款后实收" Foreground="#ff666666"/>
                    <TextBlock Text="0.00" HorizontalAlignment="Right" Foreground="#ff666666"/>
                </Grid>        <TextBlock Text="原订单信息" FontSize="12" Foreground="#ff333333" HorizontalAlignment="Center" VerticalAlignment="Center" Height="16"/>
                <Grid Height="16">
                    <TextBlock Text="订单号" Foreground="#ff666666"/>
                    <TextBlock Text="' . $result["out_trade_no"] . '" HorizontalAlignment="Right" Foreground="#ff666666"/>
                </Grid>
                <Grid Height="16">
                    <TextBlock Text="收银时间" Foreground="#ff666666"/>
                    <TextBlock Text="' . $result["pay_time"] . '" HorizontalAlignment="Right" Foreground="#ff666666"/>
                </Grid>
                <Grid Height="16">
                    <TextBlock Text="支付方式" Foreground="#ff666666"/>
                    <TextBlock Text="' . $pay_type_show . '" HorizontalAlignment="Right" Foreground="#ff666666"/>
                </Grid>    <Grid Height="16">
                    <TextBlock Text="流水号" Foreground="#ff666666"/>
                    <TextBlock Text="' . $result["trade_no"] . '" HorizontalAlignment="Right" Foreground="#ff666666"/>
                </Grid>    <Grid Height="16">
                    <TextBlock Text="订单金额" Foreground="#ff666666"/>
                    <TextBlock Text="' . $result["refund_amount"] . '" HorizontalAlignment="Right" Foreground="#ff666666"/>
                </Grid>        <Grid Height="16">
                    <TextBlock Text="实收" Foreground="#ff666666"/>
                    <TextBlock Text="0" HorizontalAlignment="Right" Foreground="#ff666666"/>
                </Grid>    </StackPanel>
        </Grid></xaml></pay_refundquery>';

            } else {
                $info = '<dm ok="0" info="未发生退款" remark="" openid="" no="" />';
            }
        }
        return $info;

    }

    /**
     * Notes: 列表详情页
     * Author: 秋枫红叶
     * AuthorQQ:10454228
     * Date: 2022/6/12 10:59
     * Copyright:©2019-2022, ZhaoZhanfeng.Com All Right Reserve，转载请注明出处！
     */
    public function list_detail(Request $request)
    {
        $device_id = $request->get('device_id');  //机具ID号
        $data = $request->get('data');  //数据 <pay_listdetail dm_id="dm7061310311" authcode="" />
        preg_match("/dm_id=\"dm\w*\d*/", $data, $dmids);
        // $out_trade_no = str_replace(['"dm_id="dm', '"', 'dm_id=dm'], '', $dmids[0]);
        $out_trade_no = str_replace(['"dm_id="dm', '"', 'dm_id=dm'], '', $dmids[0]);
     /*   $data = ['device_id' => $device_id, 'out_trade_no' => $out_trade_no, 'device_type' => 'y_plugin_1'];
        $result = $this->order_query($data);*/

        // $a = array('a', '_', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
        // $b = str_ireplace($a, "", $out_trade_no);
        // $day = substr($b, 0, 8);
        // $table = 'csorders';
        $orderdata = array();
        // if (Schema::hasTable($table)) {
        //     $orderdata = DB::table($table)->orWhere('out_trade_no', $out_trade_no)
        //         ->orWhere('trade_no', $out_trade_no)
        //         ->first();

        // } else {\
            $orderdata = DB::table('orders')->orWhere('out_trade_no', $out_trade_no)
                ->orWhere('trade_no', $out_trade_no)
                ->first();
        // }


        if (!$orderdata) {
            $info = '<pay_listdetail ok="0" dm_id="" staff="" total="" paytotal="0" paydt="" payid="" paytype="" paycoupon="0">';
            $info .= '<refund dt="" total="0"/></pay_listdetail>';
        } else {
            $result=[
                'ways_source' => $orderdata->ways_source,
                'total_amount' => $orderdata->total_amount,
                'pay_time' => $orderdata->pay_time,
                'status' => $orderdata->status,
                'trade_no' => $orderdata->trade_no,
                'refund_time' => $orderdata->updated_at,
            ];
            if ($result['ways_source'] == 'alipay') {
                $paytype = '&#x652F;&#x4ED8;&#x5B9D;';
            } elseif ($result['ways_source'] == 'weixin') {
                $paytype = '&#x5FAE;&#x4FE1;&#x652F;&#x4ED8;';
            } else {
                $paytype = '&#x94F6;&#x8054;&#x5361;';
            }
            if ($result['status'] == 6) {
                $info = '<pay_listdetail ok="1" dm_id="' . $out_trade_no . '" staff="" total="0" paytotal="0" paydt="' . $result['pay_time'] . '" payid="' . $result['trade_no'] . '" paytype="' . $paytype . '" paycoupon="0">';
                $info .= '<refund dt="' . $result['refund_time'] . '" total="-' . $result['total_amount'] . '"/></pay_listdetail>';
            } else {
                $info = '<pay_listdetail ok="1" dm_id="' . $out_trade_no . '" staff="" total="' . $result['total_amount'] . '" paytotal="' . $result['total_amount'] . '" paydt="' . $result['pay_time'] . '" payid="' . $result['trade_no'] . '" paytype="' . $paytype . '" paycoupon="0">';
                $info .= '<refund dt="" total="0"/></pay_listdetail>';
            }
        }
        return $info;
    }

    /**
     * Notes: 检测网络状态
     * Author: 秋枫红叶
     * AuthorQQ:10454228
     * Date: 2022/6/13 20:23
     * Copyright:©2019-2022, ZhaoZhanfeng.Com All Right Reserve，转载请注明出处！
     * @param Request $request
     * @return string
     */
    public function device_check(Request $request)
    {
        $device_id = $request->get('device_id');  //机具ID号
        $data = $request->get('data');  //数据 <pay_listdetail dm_id="dm7061310311" authcode="" />
        $Device = Device::where('device_no', $device_id)->first();

        if (!$Device) {
            $error = '<device_check ok="0"/>';
        } else {
            $error = '<device_check ok="1"/>';
        }
        return $error;
    }

    /**
     * 获取订单列表
     */
    public function getlist(Request $request)
    {
        $device_id = $request->get('device_id');  //机具ID号
        $data = $request->get('data');  //数据 <pay_list pagesize="8" pageindex="1" paytype="207,208" paystate="1,0,2" payover="1,0" />
        preg_match("/pageindex=\"\d+/", $data, $pageindex);
        preg_match("/\d+/", $pageindex[0], $pageindex);
        preg_match("/pagesize=\"\d+/", $data, $pagesize);
        preg_match("/\d+/", $pagesize[0], $pagesize);
        $pageindex = 1;  //当前码
        $pagesize = 10;  //每页的数量

        /*$day = date('Ymd');
        $table = 'orders_' . $day;
        $orderdata = array();
        if (Schema::hasTable($table)) {
            $obj = DB::table($table);
        } else {
            $obj = DB::table('orders');
        }
        $isjiaoban = 2;
        $where[] = ['device_id', '=', $device_id];
        $where[] = ['isjiaoban', '<', $isjiaoban];  //默认没有交班的状态
        $obj = $obj->where($where)->whereIn('pay_status', [1, 6])->orderBy('created_at', 'desc');
        $count = $obj->count();
        $listData = $this->page2($obj, ['p' => $pageindex, 'l' => $pagesize])->get();
        $page_count = ceil($count / $pagesize);
        $this->parse_data($listData, $pageindex, $page_count, 'xml', $pagesize);*/
        $created_at= date("Y-m-d 00:00:00", strtotime("-1 day"));
        $table = 'orders';

        $sql = "SELECT * from " . $table . " where device_id=:device_id and created_at>=:created_at and coupon_type<2";
        $list_data = DB::select($sql, ['device_id' => $device_id,'created_at'=>$created_at]);
        $page_count = count($list_data);
        $page_start = bcmul(bcsub($pageindex, 1, 0), $pagesize, 0);
        $page_end = bcmul($pageindex, $pagesize, 0);

        // $sql = "SELECT * from " . $yesterday_table . " where device_id=:device_id1 and isjiaoban<2 union all select * from ". $today_table ." where device_id=:device_id2 and isjiaoban<2 limit {$page_start},{$page_end}";
        // $list_data = DB::select($sql, ['device_id1' => $device_id,'device_id2' => $device_id]);
       // var_export($list_data);
       
        $this->parse_data($list_data, $pageindex, $page_count, 'xml', $pagesize);




    }

    public function parse_data($data, $page = 1, $page_count = 0, $dtype = "xml", $pagesize)
    {
        if ($dtype == 'xml') {
            // 生成xml格式数据
            header("content-type:text/xml;charset=utf8");
            echo '<pay_list ok="1" last_id="0" pageindex="' . $page . '" pagesize="' . $pagesize . '" count="' . $page_count . '">';

            foreach ($data as $key => $row) {
                if ($row->ways_source == 'weixin') {
                    $pay_type1 = 2;
                } elseif ($row->ways_source == 'alipay') {
                    $pay_type1 = 3;
                } else {
                    $pay_type1 = 4;
                }
                echo PHP_EOL;
                echo '<list dm_id="' . $row->out_trade_no . '" pay_dt="' . date('H:i:s', strtotime($row->pay_time)) . '" pay_total="' . bcmul($row->buyer_pay_amount, 100, 0) . '" pay_type1="' . $pay_type1 . '" />';
            }
            echo PHP_EOL;
            echo '</pay_list>';
        } else {
            // 生成json格式数据
            header("content-type:text/xml;charset=utf8");
            echo json_encode($data, JSON_UNESCAPED_UNICODE);
        }
    }

    /** 自定义分面
     * @param $obj
     * @param string $request
     * @return mixed
     */
    public function page2($obj, $request = '')
    {

        if (empty($request))
            $request = app('request');

        $this->p = abs(trim($request['p']));
        $this->l = abs(trim($request['l']));

        $this->needpage = true;

        $start = abs(($this->p - 1) * $this->l);
        return $obj->offset($start)->limit($this->l);
    }

    /**
     * 交班
     */
    public function handover(Request $request)
    {
        $yesterday = date("Y-m-d 00:00:00", strtotime("-1 day"));
        $table = 'orders';
        $obj = DB::table($table);
        $device_id = $request->get('device_id');  //机具ID号
        $coupon_type = 0;
        $where[] = ['device_id', '=', $device_id];
        $where[] = ['coupon_type', '=', $coupon_type];  //默认没有交班的状态
        //统计SQL
        $format_data = array(
            "prev_dt" => "",
            "last_dt" => "",
            "pay_count" => 0,
            "pay_total" => 0,
            "refund_count" => 0,
            "refund_total" => 0,
            'alipay' => array(
                "pay_count" => 0,
                "pay_total" => 0,
                "refund_count" => 0,
                "refund_total" => 0
            ),
            'weixin' => array(
                "pay_count" => 0,
                "pay_total" => 0,
                "refund_count" => 0,
                "refund_total" => 0
            ),
            'unipay' => array(
                "pay_count" => 0,
                "pay_total" => 0,
                "refund_count" => 0,
                "refund_total" => 0
            )
        );

        $sql = "SELECT count( `id` ) as num,  sum( `total_amount`) as total_amount,sum( `refund_amount`) as refund_amount, `ways_source`, `pay_status`,min( `created_at`  ) as start_time, max( `created_at` ) as end_time,store_name  from " . $table . " where `pay_status` in(1,6) and coupon_type<2 and `device_id` =:device_id and `created_at` >=:created_at GROUP BY `ways_source`, `pay_status`";
        $today_data = DB::select($sql, ['device_id' => $device_id,'created_at' => $yesterday]);
        //var_export($today_data);
        $format_data = $this->format_data($today_data, $format_data);
                                // file_put_contents('b534346.log',var_export($format_data,true)."\r\n",FILE_APPEND);
        // $sql = "SELECT count( `id` ) as num,  sum( `total_amount`) as total_amount,sum( `refund_amount`) as refund_amount, `ways_source`, `pay_status`,min( `created_at`  ) as start_time, max( `created_at` ) as end_time,store_name  from " . $yesterday_table . " where `pay_status` in(1,6) and isjiaoban<2 and `device_id` =:device_id  GROUP BY `ways_source`, `pay_status`";
        // $yestday_data = DB::select($sql, ['device_id' => $device_id]);
        // $format_data = $this->format_data($yestday_data, $format_data);

        $sql2 = "update `orders` set `coupon_type`='1' where `device_id`='".$device_id."' and `coupon_type`='0' and `created_at`>='".$yesterday."'";
        
        // update `orders` set `coupon_type`='1' where `device_id`='969696' and `coupon_type`='0' and `created_at`>='2022-07-11 00:00:00'
        $res=DB::update($sql2);
        header("content-type:text/xml;charset=utf8");
        echo '<handover ok="1" last_id="0" prev_dt="' . $format_data["prev_dt"] . '" last_dt="' . $format_data["last_dt"] . '" pay_count="' . $format_data["pay_count"] . '" pay_total="' . $format_data["pay_total"] . '" refund_count="' . $format_data["refund_count"] . '" refund_total="-' . $format_data["refund_total"] . '">
<pay pay_type="2" pay_typename="支付宝" pay_count="' . $format_data["alipay"]["pay_count"] . '" pay_total="' . $format_data["alipay"]["pay_total"] . '" refund_count="' . $format_data["alipay"]["refund_count"] . '" refund_total="-' . $format_data["alipay"]["refund_total"] . '"/>
<pay pay_type="1" pay_typename="微信" pay_count="' . $format_data["weixin"]["pay_count"] . '" pay_total="' . $format_data["weixin"]["pay_total"] . '" refund_count="' . $format_data["weixin"]["refund_count"] . '" refund_total="-' . $format_data["weixin"]["refund_total"] . '"/>
<pay pay_type="3" pay_typename="银联卡" pay_count="' . $format_data["unipay"]["pay_count"] . '" pay_total="' . $format_data["unipay"]["pay_total"] . '" refund_count="' . $format_data["unipay"]["refund_count"] . '" refund_total="-' . $format_data["unipay"]["refund_total"] . '"/>
</handover>';
    }

    /**
     * 确认交班
     */
    public function over(Request $request)
    {
        $yesterday = date("Y-m-d 00:00:00", strtotime("-1 day"));
        $table = 'orders';
        $obj = DB::table($table);
        $device_id = $request->get('device_id');  //机具ID号
        $sql2 = "update `orders` set `coupon_type`='2' where `device_id`='".$device_id."' and `coupon_type`='1' and `created_at`>='".$yesterday."'";
        DB::update($sql2);
        // $sql2 = 'update ' . $table . ' set coupon_type=2 where device_id=' . $device_id . ' and coupon_type=1';
        // DB::update($sql2);
    }

    /**
     * 打印
     */
    public function printpay(Request $request)
    {
        $created_at = date("Y-m-d 00:00:00", strtotime("-1 day"));
        $yesterday_table = 'orders';

        $obj = DB::table($yesterday_table);
        $device_id = $request->get('device_id');  //机具ID号
        $coupon_type = 1;
        $where[] = ['device_id', '=', $device_id];
        $where[] = ['coupon_type', '=', $coupon_type];  //默认没有交班的状态
        //统计SQL
        $format_data = array(
            "store_name" => "",
            "prev_dt" => "",
            "last_dt" => "",
            "pay_count" => 0,
            "pay_total" => 0,
            "refund_count" => 0,
            "refund_total" => 0,
            'alipay' => array(
                "pay_count" => 0,
                "pay_total" => 0,
                "refund_count" => 0,
                "refund_total" => 0
            ),
            'weixin' => array(
                "pay_count" => 0,
                "pay_total" => 0,
                "refund_count" => 0,
                "refund_total" => 0
            ),
            'unipay' => array(
                "pay_count" => 0,
                "pay_total" => 0,
                "refund_count" => 0,
                "refund_total" => 0
            )
        );

        // $sql = "SELECT count( `id` ) as num,  sum( `total_amount`) as total_amount,  sum( `refund_amount`) as refund_amount, `ways_source`, `pay_status`,min( `created_at`  ) as start_time, max( `created_at` ) as end_time,store_name  from " . $today_table . " where `pay_status` in(1,6) and isjiaoban=1 and `device_id` =:device_id  GROUP BY `ways_source`, `pay_status`";
        // $today_data = DB::select($sql, ['device_id' => $device_id]);
        // $format_data = $this->format_data($today_data, $format_data);
        $sql = "SELECT count( `id` ) as num,  sum( `total_amount`) as total_amount,  sum( `refund_amount`) as refund_amount, `ways_source`, `pay_status`,min( `created_at`  ) as start_time, max( `created_at` ) as end_time,store_name  from " . $yesterday_table . " where `pay_status` in(1,6) and coupon_type=1 and `device_id` =:device_id and `created_at` >=:created_at  GROUP BY `ways_source`, `pay_status`";
        $yestday_data = DB::select($sql, ['device_id' => $device_id,'created_at'=>$created_at]);
        $format_data = $this->format_data($yestday_data, $format_data);


        header("content-type:text/xml;charset=utf8");
        /*echo '<handover ok="1" last_id="0" prev_dt="'.$format_data["prev_dt"].'" last_dt="'.$format_data["last_dt"].'" pay_count="'.$format_data["pay_count"].'" pay_total="'.$format_data["pay_total"].'" refund_count="'.$format_data["refund_count"].'" refund_total="-'.$format_data["refund_total"].'">
<pay pay_type="3" pay_typename="支付宝" pay_count="'.$format_data["alipay"]["pay_count"].'" pay_total="'.$format_data["alipay"]["pay_total"].'" refund_count="'.$format_data["alipay"]["refund_count"].'" refund_total="-'.$format_data["alipay"]["refund_total"].'"/>
<pay pay_type="2" pay_typename="微信" pay_count="'.$format_data["weixin"]["pay_count"].'" pay_total="'.$format_data["weixin"]["pay_total"].'" refund_count="'.$format_data["weixin"]["refund_count"].'" refund_total="-'.$format_data["weixin"]["refund_total"].'"/>
<pay pay_type="4" pay_typename="银联卡" pay_count="'.$format_data["unipay"]["pay_count"].'" pay_total="'.$format_data["unipay"]["pay_total"].'" refund_count="'.$format_data["unipay"]["refund_count"].'" refund_total="-'.$format_data["unipay"]["refund_total"].'"/>
</handover>';*/
        echo '\x1b\x40
\x1c\x26
\x1b\x74\x00
           ' . $format_data["store_name"] . '

\x1b\x61\x01\x1D\x21\x10收银交接单
\x1b\x40

设备:' . $device_id . '
--------------------------------
上次交接班时间：' . $format_data["prev_dt"] . '
本次交接班时间：' . $format_data["last_dt"] . '
--------------------------------
	 收银方式分组统计	 
--------------------------------
             支付宝
收银笔数：                ' . $format_data["alipay"]["pay_count"] . '
收银金额：                ￥' . $format_data["alipay"]["pay_total"] . '
退款笔数：                ' . $format_data["alipay"]["refund_count"] . '
退款金额：                ￥' . $format_data["alipay"]["refund_total"] . '
--------------------------------
             微信
收银笔数：                ' . $format_data["weixin"]["pay_count"] . '
收银金额：                ￥' . $format_data["weixin"]["pay_total"] . '
退款笔数：                ' . $format_data["weixin"]["refund_count"] . '
退款金额：                ￥' . $format_data["weixin"]["refund_total"] . '
--------------------------------
             银联
收银笔数：                ' . $format_data["alipay"]["pay_count"] . '
收银金额：                ￥' . $format_data["alipay"]["pay_total"] . '
退款笔数：                ' . $format_data["alipay"]["refund_count"] . '
退款金额：                ￥' . $format_data["alipay"]["refund_total"] . '



--------------------------------
	      本班次合计
--------------------------------
收银笔数：                ' . $format_data["pay_count"] . '
收银金额：                ￥' . $format_data["pay_total"] . '
退款笔数：                ' . $format_data["refund_count"] . '
退款金额：                ￥' . $format_data["refund_total"] . '


\x0d\x0a
\x0d\x0a
\x0d\x0a
\x0d\x0a
\x1B\x69
';

    }


    /**
     * Notes:数据格式化
     * Author: 秋枫红叶
     * AuthorQQ:10454228
     * Date: 2022/6/8 21:07
     * Copyright:©2019-2022, ZhaoZhanfeng.Com All Right Reserve，转载请注明出处！
     * @param $data 原数据
     * @param $format_data 格式后的数据
     * @return mixed
     */

    public function format_data($data, $format_data)
    {
        foreach ($data as $k => $v) {
            $format_data['store_name'] = $v->store_name;
            if ($format_data['prev_dt'] == 0) {
                $format_data['prev_dt'] = $v->start_time;
            }

            if ($v->start_time < $format_data['prev_dt']) {
                $format_data['prev_dt'] = $v->start_time;
            }
            if ($v->end_time > $format_data['last_dt']) {
                $format_data['last_dt'] = $v->end_time;
            }
            if ($v->pay_status == 1) {  //支付成功
                $format_data['pay_count'] = bcadd($format_data['pay_count'], $v->num, 0);
                $format_data['pay_total'] = bcadd($format_data['pay_total'], $v->total_amount, 2);
                if ($v->ways_source == 'weixin') {
                    $format_data['weixin']['pay_count'] = bcadd($format_data['weixin']['pay_count'], $v->num, 0);
                    $format_data['weixin']['pay_total'] = bcadd($format_data['weixin']['pay_total'], $v->total_amount, 2);
                } elseif ($v->ways_source == 'alipay') {
                    $format_data['alipay']['pay_count'] = bcadd($format_data['alipay']['pay_count'], $v->num, 0);
                    $format_data['alipay']['pay_total'] = bcadd($format_data['alipay']['pay_total'], $v->total_amount, 2);
                } elseif ($v->ways_source == 'unionpay') {
                    $format_data['unipay']['pay_count'] = bcadd($format_data['unipay']['pay_count'], $v->num, 0);
                    $format_data['unipay']['pay_total'] = bcadd($format_data['unipay']['pay_total'], $v->total_amount, 2);
                }
            } else {//退款的
                $format_data['refund_count'] = bcadd($format_data['refund_count'], $v->num, 0);
                $format_data['refund_total'] = bcadd($format_data['refund_total'], $v->refund_amount, 2);
                if ($v->ways_source == 'weixin') {
                    $format_data['weixin']['refund_count'] = bcadd($format_data['weixin']['refund_count'], $v->num, 0);
                    $format_data['weixin']['refund_total'] = bcadd($format_data['weixin']['refund_total'], $v->refund_amount, 2);
                } elseif ($v->ways_source == 'alipay') {
                    $format_data['alipay']['refund_count'] = bcadd($format_data['alipay']['refund_count'], $v->num, 0);
                    $format_data['alipay']['refund_total'] = bcadd($format_data['alipay']['refund_total'], $v->refund_amount, 2);
                } elseif ($v->ways_source == 'unionpay') {
                    $format_data['unipay']['refund_count'] = bcadd($format_data['unipay']['refund_count'], $v->num, 0);
                    $format_data['unipay']['refund_total'] = bcadd($format_data['unipay']['refund_total'], $v->refund_amount, 2);
                }
            }
        }
        return $format_data;
    }

    /**
     *注册第1步
     * @desc:
     * @author：秋枫红叶
     * @authorQQ：10454228
     * @date:更新时间2022/6/8 15:27
     * copyright：copyright©2020-2021,ZhaoZhanfeng.com All Rights Reserved
     */
    public function app_device_register(Request $request)
    {
        $device_id = $request->get('initkey');  //后台生成的 外插号
        $Device = Device::where('device_no', $device_id)->first();
        if (!$Device) {
            $info = '<dm ok="0" device_id=""  info="注册失败!" />';
        } else {
            $info = '<dm ok="1" device_id="' . $Device->device_no . '"  info="设备已成功注册!" />';
        }
        return $info;
    }

    /**
     * 注册第2步
     * @desc:
     * @author：秋枫红叶
     * @authorQQ：10454228
     * @date:更新时间2022/6/8 15:27
     * copyright：copyright©2020-2021,ZhaoZhanfeng.com All Rights Reserve     *
     */
    public function logoApi(Request $request)
    {
        $device_id = $request->get('device_id');  //后台生成的 外插号
        $Device = Device::where('device_no', $device_id)->first();
        if (!$Device) {
            $info = '<dm ok="0" device_id=""  info="获取失败!" />';
        } else {
            $info = '<xml>
		            <ok>1</ok>
		            <info>success</info>
		            <path>http://pay.zgjindoufu.com/register/14_download_2.zip</path>
		         </xml>';
        }
        return $info;
    }

    //扫一扫收款
    public function scan_pay($data)
    {
        try {
            $check_data = [
                'total_amount' => '付款金额',
                'code' => '付款码编号',
                'device_id' => '设备编号',
                'device_type' => '设备类型'
            ];
            $check = $this->check_required($data, $check_data);
            if ($check) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $check
                ];
                return $this->return_data($err);
            }
            $code = $data['code'];
            $total_amount = $data['total_amount'];
            $shop_price = isset($data['shop_price']) ? $data['shop_price'] : $data['total_amount'];
            $device_id = $data['device_id'];
            $device_type = $data['device_type'];
            $shop_name = isset($data['shop_name']) ? $data['shop_name'] : "扫一扫付款";
            $shop_desc = isset($data['shop_desc']) ? $data['shop_desc'] : "扫一扫付款";
            $other_no = isset($data['other_no']) ? $data['other_no'] : "";
            $qwx_no = isset($data['qwx_no']) ? $data['qwx_no'] : "";
            $remark = isset($data['remark']) ? $data['remark'] : "";
            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "0";
            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';
            } else {
                //银豹
                if ($device_type == "pospal") {
                    $merchant_id = '0';
                    $merchant_name = '0';
                    $store_id = $device_id;
                    $config_id = '';
                } else {
                    $Device = Device::where('device_type', $device_type)
                        ->where('device_no', $device_id)
                        ->select('merchant_id', 'merchant_name', 'store_id', 'config_id')
                        ->first();

                    if (!$Device) {
                        $err = [
                            'return_code' => 'FALL',
                            'return_msg' => '设备未绑定',
                        ];
                        return $err;
                    }

                    $merchant_id = $Device->merchant_id;
                    $merchant_name = $Device->merchant_name;
                    $store_id = $Device->store_id;
                    $config_id = $Device->config_id;
                }


            }
            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'result_code' => '',
                'result_msg' => '',
                'other_no' => $other_no,
                'store_id' => $store_id,
                'ways_source' => '',
                'ways_source_desc' => '',
                'total_amount' => $total_amount,
            ];


            //请求参数
            $data = [
                'config_id' => $config_id,
                'merchant_id' => $merchant_id,
                'merchant_name' => $merchant_name,
                'code' => $code,
                'total_amount' => $total_amount,
                'shop_price' => $shop_price,
                'remark' => $remark,
                'device_id' => $device_id,
                'shop_name' => $shop_name,
                'shop_desc' => $shop_desc,
                'store_id' => $store_id,
                'other_no' => $other_no,
                'qwx_no' => $qwx_no,
            ];
            $pay_obj = new PayBaseController();
            $scan_pay_public = $pay_obj->scan_pay_public($data);

            $tra_data_arr = json_decode($scan_pay_public, true);

            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $tra_data_arr['message']
                ];
                return $err;
            }


            //用户支付成功
            if ($tra_data_arr['pay_status'] == '1') {
                //微信，支付宝支付凭证
                $re_data['result_code'] = 'SUCCESS';
                $re_data['result_msg'] = '支付成功';
                $re_data['merchant_id'] = $merchant_id;
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['out_transaction_id'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['pay_time'] = date('Y-m-d H:i:s', strtotime(isset($tra_data_arr['data']['pay_time']) ? $tra_data_arr['data']['pay_time'] : time()));
                $re_data['ways_source'] = $tra_data_arr['data']['ways_source'];

                //
                if ($re_data['ways_source'] == 'alipay') {
                    $re_data['ways_source_desc'] = "支付宝";
                }
                if ($re_data['ways_source'] == 'weixin') {
                    $re_data['ways_source_desc'] = "微信支付";
                }
                if ($re_data['ways_source'] == 'jd') {
                    $re_data['ways_source_desc'] = "京东支付";
                }
                if ($re_data['ways_source'] == 'unionpay') {
                    $re_data['ways_source_desc'] = "银联";
                }


            } elseif ($tra_data_arr['pay_status'] == '2') {
                //正在支付
                $re_data['ways_source'] = $tra_data_arr['data']['ways_source'];
                $re_data['result_code'] = 'USERPAYING';
                $re_data['result_msg'] = '用户正在支付';
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['total_amount'] = $tra_data_arr['data']['total_amount'];
                $re_data['merchant_id'] = $merchant_id;
            } else {
                //其他错误
                $re_data['result_code'] = 'FALL';
                $re_data['result_msg'] = $tra_data_arr['message'];
            }

            return $re_data;


        } catch (\Exception $exception) {

            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine(),
            ];
            return $err;
        }

    }

    //动态二维码收款
    public function qr_pay(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);
            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            $total_amount = $data['total_amount'];
            $shop_price = isset($data['shop_price']) ? $data['shop_price'] : $data['total_amount'];
            $device_id = $data['device_id'];
            $device_type = $data['device_type'];
            $ways_source = $data['ways_source'];
            $ways_type = $data['ways_type'];
            $notify_url = isset($data['notify_url']) ? $data['notify_url'] : "";
            $shop_name = isset($data['shop_name']) ? $data['shop_name'] : "扫一扫付款";
            $shop_desc = isset($data['shop_desc']) ? $data['shop_desc'] : "扫一扫付款";
            $other_no = isset($data['other_no']) ? $data['other_no'] : "";
            $remark = isset($data['remark']) ? $data['remark'] : "";


            $check_data = [
                'total_amount' => '付款金额',
                'ways_type' => '支付方式',
                'device_id' => '设备编号',
                'device_type' => '设备类型'
            ];
            $check = $this->check_required($data, $check_data);
            if ($check) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $check,
                ];
                return $this->return_data($err);
            }

            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "";


            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';

            } else {
                $Device = Device::where('device_type', $device_type)
                    ->where('device_no', $device_id)
                    ->first();

                if (!$Device) {
                    $err = [
                        'return_code' => 'FALL',
                        'return_msg' => '设备未绑定',
                    ];
                    return $this->return_data($err);
                }

                $merchant_id = $Device->merchant_id;
                $merchant_name = $Device->merchant_name;
                $store_id = $Device->store_id;
                $config_id = $Device->config_id;
            }


            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'other_no' => $other_no,
                'store_id' => $store_id,
                'ways_source' => $ways_source,
                'ways_source_desc' => '',
            ];

            //请求参数
            $data = [
                'config_id' => $config_id,
                'merchant_id' => $merchant_id,
                'merchant_name' => $merchant_name,
                'total_amount' => $total_amount,
                'shop_price' => $shop_price,
                'remark' => $remark,
                'device_id' => $device_id,
                'shop_name' => $shop_name,
                'shop_desc' => $shop_desc,
                'store_id' => $store_id,
                'other_no' => $other_no,
                'ways_source' => $ways_source,
                'notify_url' => $notify_url,
                'ways_type' => $ways_type,

            ];
            $pay_obj = new PayBaseController();
            $scan_pay_public = $pay_obj->qr_pay_public($data);
            $tra_data_arr = json_decode($scan_pay_public, true);


            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $tra_data_arr['message'],
                ];
                return $this->return_data($err);
            }


            //返回数据成功
            $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
            $re_data['code_url'] = $tra_data_arr['data']['code_url'];
            $re_data['store_name'] = $tra_data_arr['data']['store_name'];


            if ($re_data['ways_source'] == 'alipay') {
                $re_data['ways_source_desc'] = "支付宝";
            }
            if ($re_data['ways_source'] == 'weixin') {
                $re_data['ways_source_desc'] = "微信支付";
            }
            if ($re_data['ways_source'] == 'jd') {
                $re_data['ways_source_desc'] = "京东支付";
            }
            if ($re_data['ways_source'] == 'unionpay') {
                $re_data['ways_source_desc'] = "银联";
            }


            return $this->return_data($re_data);


        } catch (\Exception $exception) {

            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine(),
            ];
            return $this->return_data($err);
        }

    }

    //静态二维码
    public function qr_auth_pay(Request $request)
    {

        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);


            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            $device_id = $data['device_id'];
            $device_type = $data['device_type'];
            $other_no = isset($data['other_no']) ? $data['other_no'] : "";
            $notify_url = isset($data['notify_url']) ? $data['notify_url'] : '';

            $check_data = [
                'device_id' => '设备编号',
                'device_type' => '设备类型'
            ];
            $check = $this->check_required($data, $check_data);
            if ($check) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $check,
                ];
                return $this->return_data($err);
            }


            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "";


            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';
                $store_name = '';
                $Store = Store::where('store_id', $store_id)
                    ->select('store_short_name')
                    ->first();
                if ($Store) {
                    $store_name = $Store->store_short_name;
                }

            } else {
                $Device = Device::where('device_type', $device_type)
                    ->where('device_no', $device_id)
                    ->first();

                if (!$Device) {
                    $err = [
                        'return_code' => 'FALL',
                        'return_msg' => '设备未绑定',
                    ];
                    return $this->return_data($err);
                }

                $merchant_id = $Device->merchant_id;
                $merchant_name = $Device->merchant_name;
                $store_id = $Device->store_id;
                $store_name = $Device->store_name;

            }

            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'other_no' => $other_no,
                'store_id' => $store_id,
            ];

            $server = $request->server();
            $server['SERVER_NAME'];
            $code_url = 'https://' . $server['SERVER_NAME'] . '/qr?store_id=' . $store_id . '&merchant_id=' . $merchant_id . '';


            //返回数据成功
            $re_data['out_trade_no'] = '';
            $re_data['code_url'] = $code_url;
            $re_data['store_name'] = $store_name;

            return $this->return_data($re_data);


        } catch (\Exception $exception) {

            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine(),];
            return $this->return_data($err);
        }


    }

    //店铺通道开通类型
    public function store_pay_ways(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);
            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }


            $device_id = $data['device_id'];
            $device_type = $data['device_type'];
            $scan_amount = "";

            $check_data = [
                'device_id' => '设备编号',
                'device_type' => '设备类型'
            ];
            $check = $this->check_required($data, $check_data);
            if ($check) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $check,
                ];
                return $this->return_data($err);
            }


            $Device = Device::where('device_type', $device_type)
                ->where('device_no', $device_id)
                ->first();

            if (!$Device) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '设备未绑定',
                ];
                return $this->return_data($err);
            }

            $store_id = $Device->store_id;
            $merchant_id = $Device->merchant_id;
            $store_name = $Device->store_name;
            $config_id = $Device->config_id;


            //
            $MqttConfig = MqttConfig::where('config_id', $config_id)->first();
            if (!$MqttConfig) {
                $MqttConfig = MqttConfig::where('config_id', '1234')->first();
            }

            if (!$MqttConfig) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '未配置消息推送',
                ];
                return $this->return_data($err);
            }

            $mq_server = $MqttConfig->server;
            $mq_topic = $MqttConfig->topic;
            $mq_port = $MqttConfig->port;
            $mq_group_id = $MqttConfig->group_id;
            $mq_user_name = "Signature|" . $MqttConfig->access_key_id . "|" . $MqttConfig->instance_id . "";

            $str = '' . $MqttConfig->group_id . '@@@' . $device_id . '';
            $key = $MqttConfig->access_key_secret;
            $str = mb_convert_encoding($str, "UTF-8");
            $mq_user_password = base64_encode(hash_hmac("sha1", $str, $key, true));


            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'store_id' => $store_id,
                'config_id' => $config_id,
                'merchant_id' => $merchant_id,
                'store_name' => $store_name,
                'scan_amount' => $scan_amount,
                'mq_server' => $mq_server,
                'mq_topic' => $mq_topic,
                'mq_port' => $mq_port,
                'mq_group_id' => $mq_group_id,
                'client_id' => $mq_group_id . '@@@' . $device_id,
                'mq_user_name' => $mq_user_name,
                'mq_user_password' => $mq_user_password,
            ];


            $data = DB::table('store_ways_desc')
                ->join('store_pay_ways', 'store_pay_ways.ways_type', '=', 'store_ways_desc.ways_type')
                ->where('store_pay_ways.store_id', $store_id)
                ->where('store_pay_ways.status', 1)
                ->where('store_pay_ways.is_close', 0)
                ->select('store_pay_ways.ways_type', 'store_pay_ways.ways_desc', 'store_pay_ways.ways_source', 'store_pay_ways.sort', 'store_pay_ways.rate')
                ->orderBy('store_pay_ways.sort', 'asc')
                ->get();

            //如果为空 看下是否为分店
            if ($data->isEmpty()) {
                $store = Store::where('store_id', $store_id)
                    ->select('pid')
                    ->first();
                //查总店
                if ($store && $store->pid) {
                    $store = Store::where('id', $store->pid)
                        ->select('store_id')
                        ->first();
                    if ($store) {
                        $data = DB::table('store_ways_desc')
                            ->join('store_pay_ways', 'store_pay_ways.ways_type', '=', 'store_ways_desc.ways_type')
                            ->where('store_pay_ways.store_id', $store->store_id)
                            ->where('store_pay_ways.status', 1)
                            ->where('store_pay_ways.is_close', 0)
                            ->select('store_pay_ways.ways_type', 'store_pay_ways.ways_desc', 'store_pay_ways.ways_source', 'store_pay_ways.sort', 'store_pay_ways.rate')
                            ->orderBy('store_pay_ways.sort', 'asc')
                            ->get();
                    }
                }
            }


            //返回数据成功
            $re_data['data'] = $data;


            return $this->return_data($re_data);


        } catch (\Exception $exception) {

            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine(),];
            return $this->return_data($err);
        }
    }


    //小程序收款
    public function mini_pay(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);

            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }
            $merchant_id = $request->get('merchant_id');
            $merchant = Merchant::where('id', $merchant_id)
                ->select('name')
                ->first();
            $merchant_name = '';
            if ($merchant) {
                $merchant_name = $merchant->name;
            }
            $store_id = $data['store_id'];
            $store = Store::where('store_id', $store_id)
                ->select('config_id', 'store_name', 'pid', 'user_id', 'is_delete', 'is_admin_close', 'is_close', 'status')
                ->first();
            if (!$store) {

                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '没有关联认证门店请联系服务商',
                    'result_code' => 'FALL',
                    'result_msg' => '没有关联认证门店请联系服务商',
                ];

                return $this->return_data($err);

            }
            //关闭的商户禁止交易
            if ($store->is_close || $store->is_admin_close || $store->is_delete) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '商户已经被服务商关闭',
                    'result_code' => 'FALL',
                    'result_msg' => '商户已经被服务商关闭',
                ];

                return $this->return_data($err);

            }

            if($store->status!=1){
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '商户已经被服务商关闭',
                    'result_code' => 'FALL',
                    'result_msg' => '商户已经被服务商关闭',
                ];
                return $this->return_data($err);
            }

            $config_id = $store->config_id;
            $store_name = $store->store_name;
            $store_pid = $store->pid;
            $tg_user_id = $store->user_id;
            $total_amount = isset($data['total_amount']) ? $data['total_amount'] : "";
            $shop_price = isset($data['total_amount']) ? $data['total_amount'] : "";
            $remark = '';
            $device_id = isset($data['device_id']) ? $data['device_id'] : "";
            $shop_name = '收款';
            $shop_desc = '收款';
            $open_id = isset($data['open_id']) ? $data['open_id'] : "";
            $ways_source = isset($data['ways_source']) ? $data['ways_source'] : "";
            $other_no = isset($data['other_no']) ? $data['other_no'] : "";
            $notify_url = isset($data['notify_url']) ? $data['notify_url'] : "";
            $pay_type = isset($data['pay_type']) ? $data['pay_type'] : "01";

            $check_data = [
                'total_amount' => '付款金额',
            ];

            $check = $this->check_required($data, $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }

            if ($other_no == "" || $other_no == "NULL") {
                $other_no = "";
            }


            if ($notify_url == "" || $notify_url == "NULL") {
                $notify_url = "";
            }
            $obj_ways = new  PayWaysController();
            $ways = $obj_ways->ways_source($ways_source, $store_id, $store_pid);
            if (!$ways) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '没有开通此类型通道',
                    'result_code' => 'FALL',
                    'result_msg' => '没有开通此类型通道',
                ];
                return $this->return_data($err);

            }

            //验证扣费模式
            list($isRun,$error)=\App\Services\Store\StoreSignService::validateSign((string)$ways->store_id,(string)$ways->company);
            if($isRun==false){
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $error,
                    'result_code' => 'FALL',
                    'result_msg' => $error,
                ];
                return $this->return_data($err);
            }


            $ways_type = $ways->ways_type;
            $data = [
                'merchant_name' => $merchant_name,
                'store_id' => $store_id,
                'merchant_id' => $merchant_id,
                'config_id' => $config_id,
                'store_name' => $store_name,
                'store_pid' => $store_pid,
                'tg_user_id' => $tg_user_id,
                'total_amount' => $total_amount,
                'shop_price' => $shop_price,
                'remark' => $remark,
                'device_id' => $device_id,
                'shop_name' => $shop_name,
                'shop_desc' => $shop_desc,
                'open_id' => $open_id,
                'ways_type' => $ways_type,
                'other_no' => $other_no,
                'notify_url' => $notify_url,
            ];
            $pay_obj = new PayBaseController();
            if ($pay_type == "01") {
                $scan_pay_public = $pay_obj->qr_auth_pay_public($data, $ways);

            } else {
                $scan_pay_public = $pay_obj->mini_app_pay_public($data, $ways);

            }
            $tra_data_arr = json_decode($scan_pay_public, true);

            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $tra_data_arr['message'],
                    'result_code' => 'FALL',
                    'result_msg' => $tra_data_arr['message'],
                ];
                return $this->return_data($err);
            }
            $re_data = [];
            //支付宝
            if ($ways_source == "alipay") {


                //随行付
                if ($ways->company == "vbill") {

                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'trade_no' => $tra_data_arr['trade_no']
                    ];
                }


                //官方支付宝
                if ($ways->company == "alipay") {

                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'trade_no' => $tra_data_arr['trade_no']
                    ];
                }

                //官方直付通
                if ($ways->company == "zft") {

                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'trade_no' => $tra_data_arr['trade_no']
                    ];
                }
                //新大陆
                if ($ways->company == "newland") {

                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'trade_no' => $tra_data_arr['trade_no']
                    ];
                }

                //快钱
                if ($ways->company == "mybank") {

                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'trade_no' => $tra_data_arr['trade_no']
                    ];
                }

                //dlb
                if ($ways->company == "dlb") {

                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'trade_no' => $tra_data_arr['reserved_transaction_id']
                    ];
                }


            }


            if ($ways_source == "weixin") {


                //随行付
                if ($ways->company == "vbill") {
                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'payTimeStamp' => $tra_data_arr['data']['payTimeStamp'],
                        'payPackage' => $tra_data_arr['data']['payPackage'],
                        'paySign' => $tra_data_arr['data']['paySign'],
                        'payAppId' => $tra_data_arr['data']['payAppId'],
                        'paynonceStr' => $tra_data_arr['data']['paynonceStr'],
                        'paySignType' => $tra_data_arr['data']['paySignType'],
                    ];
                }


                //微信官方
                if ($ways->company == "weixin") {
                    $tra_data_arr['data'] = json_decode($tra_data_arr['data'], true);
                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'payTimeStamp' => $tra_data_arr['data']['timeStamp'],
                        'payPackage' => $tra_data_arr['data']['package'],
                        'paySign' => $tra_data_arr['data']['paySign'],
                        'payAppId' => $tra_data_arr['data']['appId'],
                        'paynonceStr' => $tra_data_arr['data']['nonceStr'],
                        'paySignType' => $tra_data_arr['data']['signType'],
                    ];
                }


                //快钱
                if ($ways->company == "mybank") {
                    $tra_data_arr['data'] = json_decode($tra_data_arr['data'], true);
                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'payTimeStamp' => $tra_data_arr['data']['timeStamp'],
                        'payPackage' => $tra_data_arr['data']['package'],
                        'paySign' => $tra_data_arr['data']['paySign'],
                        'payAppId' => $tra_data_arr['data']['appId'],
                        'paynonceStr' => $tra_data_arr['data']['nonceStr'],
                        'paySignType' => $tra_data_arr['data']['signType'],
                    ];
                }

                //新大陆
                if ($ways->company == "newland") {
                    $tra_data_arr['data'] = json_decode($tra_data_arr['data'], true);
                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'payTimeStamp' => $tra_data_arr['data']['apiTimestamp'],
                        'payPackage' => $tra_data_arr['data']['apiPackage'],
                        'paySign' => $tra_data_arr['data']['apiPaysign'],
                        'payAppId' => $tra_data_arr['data']['apiAppid'],
                        'paynonceStr' => $tra_data_arr['data']['apiNoncestr'],
                        'paySignType' => $tra_data_arr['data']['apiSigntype'],
                    ];
                }
                //多啦宝
                if ($ways->company == "dlb") {
                    $tra_data_arr['data'] = json_decode($tra_data_arr['data'], true);
                    $re_data = [
                        'return_code' => 'SUCCESS',
                        'return_msg' => '数据返回成功',
                        'result_code' => 'SUCCESS',
                        'result_msg' => '数据返回成功',
                        'payTimeStamp' => $tra_data_arr['data']['TIMESTAMP'],
                        'payPackage' => $tra_data_arr['data']['PACKAGE'],
                        'paySign' => $tra_data_arr['data']['PAYSIGN'],
                        'payAppId' => $tra_data_arr['data']['APPID'],
                        'paynonceStr' => $tra_data_arr['data']['NONCESTR'],
                        'paySignType' => $tra_data_arr['data']['SIBGTYPE'],
                    ];
                }


            }


            return $this->return_data($re_data);


        } catch (\Exception $exception) {

            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine(),
            ];
            return $this->return_data($err);
        }

    }


//查询订单号状态
    public function order_query($data)
    {

        try {
            //获取请求参数
            //$data = $request->getContent();

            /*$data = json_decode($data, true);
            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }*/

            //  $other_no = isset($data['other_no']) ? $data['other_no'] : '';
            $out_trade_no = isset($data['out_trade_no']) ? $data['out_trade_no'] : "";
            /*$orderids = DB::table('orderids')->Where('out_trade_no', $out_trade_no)->first();
            if(!$orderids)
            {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '订单不存在',
                ];
                return $err;
            }else{
                $out_trade_no = $orderids->other_no;
            }*/

            // $a = array('a', '_', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
            // $b = str_ireplace($a, "", $out_trade_no);
            // $day = substr($b, 0, 8);
            $table = 'orders';
            $orderdata = array();
            // if (Schema::hasTable($table)) {
            //     $orderdata = DB::table($table)->orWhere('out_trade_no', $out_trade_no)
            //         ->orWhere('trade_no', $out_trade_no)
            //         ->first();

            // } else {
                $orderdata = DB::table('orders')->orWhere('out_trade_no', $out_trade_no)
                    ->orWhere('trade_no', $out_trade_no)->orWhere('qwx_no', $out_trade_no)
                    ->first();
            // }
            $device_id = $data['device_id'];
            $device_type = $data['device_type'];


            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "";


            if ($orderdata->status == 6) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '已退款的交易，不能从这里发起查询！',
                ];
                return $err;
            }



            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';

            } else {

                //银豹
                if ($device_type == "pospal") {
                    $merchant_id = '0';
                    $merchant_name = '0';
                    $store_id = $device_id;
                    $config_id = '';
                } else {
                    $Device = Device::where('device_type', $device_type)
                        ->where('device_no', $device_id)
                        ->first();

                    if (!$Device) {
                        $err = [
                            'return_code' => 'FALL',
                            'return_msg' => '设备未绑定',
                        ];
                        return $err;
                    }

                    $merchant_id = $Device->merchant_id;
                    $merchant_name = $Device->merchant_name;
                    $store_id = $Device->store_id;
                    $store_name = $Device->store_name;
                    $config_id = $Device->config_id;
                }

            }

            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'other_no' => $orderdata->other_no,
                'store_id' => $store_id,
            ];

            $order_foreach_public = [
                'out_trade_no' => $orderdata->out_trade_no,
                'store_id' => $orderdata->store_id,
                'ways_type' => $orderdata->ways_type,
                'config_id' => $orderdata->config_id,
                'table' => $table,
            ];

            $order_obj = new OrderController();
            $return = $order_obj->order_foreach_public($order_foreach_public);

            $tra_data_arr = json_decode($return, true);
            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $tra_data_arr['message'],
                ];
                return $err;
            }

            //用户支付成功
            if ($tra_data_arr['pay_status'] == '1') {
                //微信，支付宝支付凭证
                $re_data['result_code'] = 'SUCCESS';
                $re_data['result_msg'] = '支付成功';
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['out_transaction_id'] = $tra_data_arr['data']['out_trade_no'];
                //  $re_data['pay_time'] = date('Y-m-d H:i:s', strtotime($tra_data_arr['data']['pay_time']));
                $re_data['pay_time'] = $orderdata->pay_time;
                $re_data['ways_source'] = $tra_data_arr['data']['ways_source'];
                $re_data['pay_amount'] = isset($tra_data_arr['data']['pay_amount']) ? $tra_data_arr['data']['pay_amount'] : "";
                $re_data['total_amount'] = isset($tra_data_arr['data']['total_amount']) ? $tra_data_arr['data']['total_amount'] : "";
                $re_data['other_no'] = isset($tra_data_arr['data']['other_no']) ? $tra_data_arr['data']['other_no'] : "";
                $re_data['status'] = $orderdata->status;
                $re_data['refund_time'] = $orderdata->updated_at;
                //
                if ($re_data['ways_source'] == 'alipay') {
                    $re_data['ways_source_desc'] = "支付宝";
                }
                if ($re_data['ways_source'] == 'weixin') {
                    $re_data['ways_source_desc'] = "微信支付";
                }
                if ($re_data['ways_source'] == 'jd') {
                    $re_data['ways_source_desc'] = "京东支付";
                }
                if ($re_data['ways_source'] == 'unionpay') {
                    $re_data['ways_source_desc'] = "银联";
                }


            } elseif ($tra_data_arr['pay_status'] == '2') {
                //正在支付
                $re_data['result_code'] = 'USERPAYING';
                $re_data['result_msg'] = '用户正在支付';
                $re_data['out_trade_no'] = $tra_data_arr['data']['out_trade_no'];
                $re_data['total_amount'] = $tra_data_arr['data']['total_amount'];
            } else {
                //其他错误
                $re_data['result_code'] = 'FALL';
                $re_data['result_msg'] = $tra_data_arr['message'];
            }
            return $re_data;


        } catch (\Exception $exception) {

            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine(),];
            return $err;
        }


    }


//退款接口
    public function refund($data)
    {
        try {
            //获取请求参数

            $device_id = isset($data['device_id']) ? $data['device_id'] : "";
            $device_type = isset($data['device_type']) ? $data['device_type'] : "";
            $out_trade_no = isset($data['out_trade_no']) ? $data['out_trade_no'] : "";
            $refund_amount = isset($data['refund_amount']) ? $data['refund_amount'] : "";
            $refund_no = isset($data['refund_no']) ? $data['refund_no'] : $out_trade_no . '123';


            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "";

            // $isrefund_no = preg_match('/[a-zA-Z]/', $out_trade_no);  //是否含有字母 含字母系统订单号 不含字母平台TANSID

            // if (!$isrefund_no) {
            //     $trade_no = $out_trade_no;  //平台退款码
            //     //查询表名
            //     $orderids = DB::table('orderids')->Where('other_no', $trade_no)->first();
            //     $out_trade_no = $orderids->out_trade_no;
            // }


            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';

            } else {
                //银豹
                if ($device_type == "pospal") {
                    $merchant_id = '0';
                    $merchant_name = '0';
                    $store_id = $device_id;
                    $config_id = '';
                } else {
                    $Device = Device::where('device_type', $device_type)
                        ->where('device_no', $device_id)
                        ->first();

                    if (!$Device) {
                        $err = [
                            'return_code' => 'FALL',
                            'return_msg' => '设备未绑定',
                        ];
                        return $err;
                    }

                    $merchant_id = $Device->merchant_id;
                    $merchant_name = $Device->merchant_name;
                    $store_id = $Device->store_id;
                    $config_id = $Device->config_id;
                }

            }


            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'result_code' => '',
                'result_msg' => '',
                'store_id' => $store_id,
                'out_trade_no' => $out_trade_no,
                'refund_amount' => $refund_amount,
            ];

            //请求参数
            $data = [
                'merchant_id' => $merchant_id,
                'out_trade_no' => $out_trade_no,
                'refund_amount' => $refund_amount,
                'refund_no' => $refund_no
            ];
            $pay_obj = new OrderController();
            $scan_pay_public = $pay_obj->refund_public($data);
            $tra_data_arr = json_decode($scan_pay_public, true);

            if ($tra_data_arr['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'result_code' => 'FALL',
                    'return_msg' => $tra_data_arr['message'],
                    'other_no' => '',
                    'refund_no' => '',
                ];
                return $err;
            }

            /*  $re_data['other_no'] = $tra_data_arr['data']['other_no'];
              $re_data['refund_no'] = $tra_data_arr['data']['refund_no'];
              $re_data['result_code'] = 'SUCCESS';
              $re_data['result_msg'] = '退款成功';

              */

            $queryData = ['device_id' => $device_id, 'out_trade_no' => $out_trade_no];
            $re_data = $this->refund_query($queryData);

            return $re_data;

        } catch (\Exception $exception) {
            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine(),
            ];
            return $err;
        }


    }

//退款查询接口
    public function refund_query($data)
    {
        try {

            $trade_no = isset($data['tade_no']) ? $data['tade_no'] : "";;
            $device_id = isset($data['device_id']) ? $data['device_id'] : "";
            $device_type = isset($data['device_type']) ? $data['device_type'] : "";
            $out_trade_no = isset($data['out_trade_no']) ? $data['out_trade_no'] : "";
            $refund_no = isset($data['refund_no']) ? $data['refund_no'] : "";

            $Device = Device::where('device_no', $device_id)
                ->first();

            if (!$Device) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '设备未绑定1',
                ];
                return $err;
            }

            $store_id = $Device->store_id;

            /*
                        //查询表名
                        $orderids = DB::table('orderids')->Where('other_no', $trade_no)->first();
                        if (!$orderids) {
                            $err = [
                                'return_code' => 'FALL',
                                'return_msg' => '订单不存在',
                            ];
                            return $err;
                        } else {
                            $out_trade_no = $orderids->out_trade_no;
                        }*/

            $table = 'orders';

            $orderdata = array();
            // if (Schema::hasTable($table)) {
            //     $orderdata = DB::table($table)->orWhere('out_trade_no', $out_trade_no)
            //         ->orWhere('trade_no', $out_trade_no)
            //         ->first();

            // } else {
                $orderdata = DB::table('orders')->orWhere('out_trade_no', $out_trade_no)
                    ->orWhere('trade_no', $out_trade_no)->orWhere('qwx_no', $out_trade_no)
                    ->first();
            // }

            // var_export($orderdata);

            /*$RefundOrder = RefundOrder::where('store_id', $store_id)
                ->where('refund_no', $refund_no)
                ->select('refund_amount')
                ->first();*/

            if (!$orderdata) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '退款单号不存在',
                ];
                return $err;
            }


            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'result_code' => '',
                'result_msg' => '',
                'out_trade_no' => $out_trade_no,
                'trade_no' => $orderdata->trade_no,
                'time_end' => date("Y-m-d H:m:s", strtotime($orderdata->pay_time)),  //付款时间
                'total_fee' => $orderdata->total_amount,
                'refund_no' => $refund_no,
                'refund_amount' => $orderdata->shop_price,
                'pay_time' => $orderdata->updated_at,
                'ways_source' => $orderdata->ways_source,
                'ways_source_desc' => $orderdata->ways_source_desc,
                'status' => $orderdata->status,
                'store_name' => $orderdata->store_name,
                'merchant_name' => $orderdata->merchant_name,
            ];


            $re_data['result_code'] = 'SUCCESS';
            $re_data['result_msg'] = '退款成功';

            return $re_data;


        } catch (\Exception $exception) {

            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine(),
            ];
            return $err;
        }


    }


//对账查询
    public function order(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);


            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }


            $time_start = $data['time_start'];
            $time_end = $data['time_end'];
            $device_id = $data['device_id'];
            $device_type = $data['device_type'];


            $check_data = [
                'time_start' => '开始时间',
                'time_end' => '结束时间',
            ];
            $check = $this->check_required($data, $check_data);
            if ($check) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $check,
                ];
                return $this->return_data($err);
            }


            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "";


            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';

            } else {
                $Device = Device::where('device_type', $device_type)
                    ->where('device_no', $device_id)
                    ->first();

                if (!$Device) {
                    $err = [
                        'return_code' => 'FALL',
                        'return_msg' => '设备未绑定',
                    ];
                    return $this->return_data($err);
                }

                $merchant_id = $Device->merchant_id;
                $merchant_name = $Device->merchant_name;
                $store_id = $Device->store_id;
                $store_name = $Device->store_name;
                $config_id = $Device->config_id;
            }


            //公共返回参数

            $request_data = [
                'store_id' => $store_id,
                'merchant_id' => $merchant_id,
                'time_start' => $time_start,
                'time_end' => $time_end,

            ];
            $data = $this->order_count_public($request_data);
            if ($data['status'] != 1) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => $data['message'],
                ];
                return $this->return_data($err);
            }

            $re_data = $data['data'];
            $re_data['return_code'] = 'SUCCESS';
            $re_data['return_msg'] = '返回成功';

            return $this->return_data($re_data);


        } catch (\Exception $exception) {

            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine(),];
            return $this->return_data($err);
        }


    }

//对账统计-比较全
    public function order_count_public($data)
    {
        try {
            $store_id = $data['store_id'];
            $merchant_id = $data['merchant_id'];
            $time_start = $data['time_start'];
            $time_end = $data['time_end'];

            $where = [];
            $whereIn = [];
            $store_ids = [];

            //条件查询
            if ($store_id) {
                $where[] = ['store_id', '=', $store_id];
                $store_ids = [
                    [
                        'store_id' => $store_id,
                    ]
                ];

            } else {
                $MerchantStore = MerchantStore::where('merchant_id', $merchant_id)
                    ->select('store_id')
                    ->get();

                if (!$MerchantStore->isEmpty()) {
                    $store_ids = $MerchantStore->toArray();
                }

            }


            //是否传收银员ID
            if ($merchant_id) {
                $where[] = ['merchant_id', '=', $merchant_id];
            }

            if ($time_start) {
                $time_start = date('Y-m-d H:i:s', strtotime($time_start));
                $where[] = ['created_at', '>=', $time_start];
            }
            if ($time_end) {
                $time_end = date('Y-m-d H:i:s', strtotime($time_end));
                $where[] = ['created_at', '<=', $time_end];
            }

            //跨天操作
            $time_start_db = date('Ymd', strtotime($time_start));
            $time_end_db = date('Ymd', strtotime($time_end));
            $is_ct_time = 0;
            if ($time_start_db != $time_end_db) {
                $is_ct_time = 1;
            }


            //区间
            $e_order = '0.00';


            $day = date('Ymd', strtotime($time_end));
            $table = 'orders_' . $day;


            if (env('DB_D1_HOST')) {
                //有没有跨天
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                        $obj = DB::connection("mysql_d1")->table('order_items');

                    } else {
                        $obj = DB::connection("mysql_d1")->table('orders');
                    }
                } else {

                    if (Schema::hasTable($table)) {
                        $obj = DB::connection("mysql_d1")->table($table);

                    } else {
                        if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                            $obj = DB::connection("mysql_d1")->table('order_items');

                        } else {
                            $obj = DB::connection("mysql_d1")->table('orders');
                        }
                    }
                }
            } else {
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                        $obj = DB::table('order_items');
                    } else {
                        $obj = DB::table('orders');
                    }
                } else {

                    if (Schema::hasTable($table)) {
                        $obj = DB::table($table);

                    } else {
                        if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                            $obj = DB::table('order_items');

                        } else {
                            $obj = DB::table('orders');
                        }
                    }
                }
            }

            if (env('DB_D1_HOST')) {
                //有没有跨天
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                        $obj1 = DB::connection("mysql_d1")->table('order_items');

                    } else {
                        $obj1 = DB::connection("mysql_d1")->table('orders');
                    }
                } else {

                    if (Schema::hasTable($table)) {
                        $obj1 = DB::connection("mysql_d1")->table($table);

                    } else {
                        if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                            $obj1 = DB::connection("mysql_d1")->table('order_items');

                        } else {
                            $obj1 = DB::connection("mysql_d1")->table('orders');
                        }
                    }
                }
            } else {
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                        $obj1 = DB::table('order_items');
                    } else {
                        $obj1 = DB::table('orders');
                    }
                } else {

                    if (Schema::hasTable($table)) {
                        $obj1 = DB::table($table);

                    } else {
                        if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                            $obj1 = DB::table('order_items');

                        } else {
                            $obj1 = DB::table('orders');
                        }
                    }
                }
            }


            if (env('DB_D1_HOST')) {
                //有没有跨天
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                        $obj2 = DB::connection("mysql_d1")->table('order_items');

                    } else {
                        $obj2 = DB::connection("mysql_d1")->table('orders');
                    }
                } else {

                    if (Schema::hasTable($table)) {
                        $obj2 = DB::connection("mysql_d1")->table($table);

                    } else {
                        if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                            $obj2 = DB::connection("mysql_d1")->table('order_items');

                        } else {
                            $obj2 = DB::connection("mysql_d1")->table('orders');
                        }
                    }
                }
            } else {
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                        $obj2 = DB::table('order_items');
                    } else {
                        $obj2 = DB::table('orders');
                    }
                } else {

                    if (Schema::hasTable($table)) {
                        $obj2 = DB::table($table);

                    } else {
                        if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                            $obj2 = DB::table('order_items');

                        } else {
                            $obj2 = DB::table('orders');
                        }
                    }
                }
            }


            if (env('DB_D1_HOST')) {
                //有没有跨天
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                        $obj3 = DB::connection("mysql_d1")->table('order_items');

                    } else {
                        $obj3 = DB::connection("mysql_d1")->table('orders');
                    }
                } else {

                    if (Schema::hasTable($table)) {
                        $obj3 = DB::connection("mysql_d1")->table($table);

                    } else {
                        if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                            $obj3 = DB::connection("mysql_d1")->table('order_items');

                        } else {
                            $obj3 = DB::connection("mysql_d1")->table('orders');
                        }
                    }
                }
            } else {
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                        $obj3 = DB::table('order_items');
                    } else {
                        $obj3 = DB::table('orders');
                    }
                } else {

                    if (Schema::hasTable($table)) {
                        $obj3 = DB::table($table);

                    } else {
                        if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                            $obj3 = DB::table('order_items');

                        } else {
                            $obj3 = DB::table('orders');
                        }
                    }
                }
            }


            if (env('DB_D1_HOST')) {
                //有没有跨天
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                        $obj4 = DB::connection("mysql_d1")->table('order_items');

                    } else {
                        $obj4 = DB::connection("mysql_d1")->table('orders');
                    }
                } else {

                    if (Schema::hasTable($table)) {
                        $obj4 = DB::connection("mysql_d1")->table($table);

                    } else {
                        if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                            $obj4 = DB::connection("mysql_d1")->table('order_items');

                        } else {
                            $obj4 = DB::connection("mysql_d1")->table('orders');
                        }
                    }
                }
            } else {
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                        $obj4 = DB::table('order_items');
                    } else {
                        $obj4 = DB::table('orders');
                    }
                } else {

                    if (Schema::hasTable($table)) {
                        $obj4 = DB::table($table);

                    } else {
                        if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                            $obj4 = DB::table('order_items');

                        } else {
                            $obj4 = DB::table('orders');
                        }
                    }
                }
            }


            if (env('DB_D1_HOST')) {
                //有没有跨天
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                        $obj5 = DB::connection("mysql_d1")->table('order_items');

                    } else {
                        $obj5 = DB::connection("mysql_d1")->table('orders');
                    }
                } else {

                    if (Schema::hasTable($table)) {
                        $obj5 = DB::connection("mysql_d1")->table($table);

                    } else {
                        if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                            $obj5 = DB::connection("mysql_d1")->table('order_items');

                        } else {
                            $obj5 = DB::connection("mysql_d1")->table('orders');
                        }
                    }
                }
            } else {
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                        $obj5 = DB::table('order_items');
                    } else {
                        $obj5 = DB::table('orders');
                    }
                } else {

                    if (Schema::hasTable($table)) {
                        $obj5 = DB::table($table);

                    } else {
                        if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                            $obj5 = DB::table('order_items');

                        } else {
                            $obj5 = DB::table('orders');
                        }
                    }
                }
            }


            if ($merchant_id) {


                $order_data = $obj->where($where)
                    ->whereIn('pay_status', [1, 6, 3])//成功+退款
                    ->where('merchant_id', $merchant_id)
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $refund_obj = RefundOrder::where('merchant_id', $merchant_id)
                    ->where($where)
                    ->select('refund_amount');


                //支付宝
                $alipay_order_data = $obj1->where($where)
                    ->whereIn('pay_status', [1, 6, 3])//成功+退款
                    ->where('ways_source', 'alipay')
                    ->where('merchant_id', $merchant_id)
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $alipay_refund_obj = RefundOrder::where('merchant_id', $merchant_id)
                    ->where('ways_source', 'alipay')
                    ->where($where)
                    ->select('refund_amount');


                //微信
                $weixin_order_data = $obj2->where($where)
                    ->whereIn('pay_status', [1, 6, 3])//成功+退款
                    ->where('ways_source', 'weixin')
                    ->where('merchant_id', $merchant_id)
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $weixin_refund_obj = RefundOrder::where('merchant_id', $merchant_id)
                    ->where('ways_source', 'weixin')
                    ->where($where)
                    ->select('refund_amount');


                //京东
                $jd_order_data = $obj3->where($where)
                    ->whereIn('pay_status', [1, 6, 3])//成功+退款
                    ->where('ways_source', 'jd')
                    ->where('merchant_id', $merchant_id)
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $jd_refund_obj = RefundOrder::where('merchant_id', $merchant_id)
                    ->where('ways_source', 'jd')
                    ->where($where)
                    ->select('refund_amount');


                //银联刷卡
                $un_order_data = $obj4->where($where)
                    ->whereIn('pay_status', [1, 6, 3])//成功+退款
                    ->whereIn('ways_type', [6005, 8005])//新大陆+京东刷卡
                    ->where('ways_source', 'unionpay')
                    ->where('merchant_id', $merchant_id)
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $un_refund_obj = RefundOrder::where('merchant_id', $merchant_id)
                    ->whereIn('type', [6005, 8005])//新大陆+京东刷卡
                    ->where('ways_source', 'unionpay')
                    ->where($where)
                    ->select('refund_amount');


                //银联扫码
                $unqr_order_data = $obj5->where($where)
                    ->whereIn('pay_status', [1, 6, 3])//成功+退款
                    ->whereNotIn('ways_type', [6005, 8005])//新大陆+京东刷卡
                    ->where('ways_source', 'unionpay')
                    ->where('merchant_id', $merchant_id)
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');

                $unqr_refund_obj = RefundOrder::where('merchant_id', $merchant_id)
                    ->whereNotIn('type', [6005, 8005])//新大陆+京东刷卡
                    ->where('ways_source', 'unionpay')
                    ->where($where)
                    ->select('refund_amount');


            } else {
                $order_data = $obj->whereIn('store_id', $store_ids)
                    ->where($where)
                    ->whereIn('pay_status', [1, 6, 3])//成功+退款
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');


                $refund_obj = RefundOrder::whereIn('store_id', $store_ids)
                    ->where($where)
                    ->select('refund_amount');

                //支付宝
                $alipay_order_data = $obj1->whereIn('store_id', $store_ids)
                    ->where($where)
                    ->whereIn('pay_status', [1, 6, 3])//成功+退款
                    ->where('ways_source', 'alipay')
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');


                $alipay_refund_obj = RefundOrder::whereIn('store_id', $store_ids)
                    ->where($where)
                    ->where('ways_source', 'alipay')
                    ->select('refund_amount');


                //微信
                $weixin_order_data = $obj2->whereIn('store_id', $store_ids)
                    ->where($where)
                    ->whereIn('pay_status', [1, 6, 3])//成功+退款
                    ->where('ways_source', 'weixin')
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');


                $weixin_refund_obj = RefundOrder::whereIn('store_id', $store_ids)
                    ->where($where)
                    ->where('ways_source', 'weixin')
                    ->select('refund_amount');


                //京东
                $jd_order_data = $obj3->whereIn('store_id', $store_ids)
                    ->where($where)
                    ->whereIn('pay_status', [1, 6, 3])//成功+退款
                    ->where('ways_source', 'jd')
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');


                $jd_refund_obj = RefundOrder::whereIn('store_id', $store_ids)
                    ->where($where)
                    ->where('ways_source', 'jd')
                    ->select('refund_amount');


                //银联刷卡
                $un_order_data = $obj4->whereIn('store_id', $store_ids)
                    ->where($where)
                    ->whereIn('pay_status', [1, 6, 3])//成功+退款
                    ->whereIn('ways_type', [6005, 8005])//新大陆+京东刷卡
                    ->where('ways_source', 'unionpay')
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');


                $un_refund_obj = RefundOrder::whereIn('store_id', $store_ids)
                    ->where($where)
                    ->where('ways_source', 'unionpay')
                    ->whereIn('type', [6005, 8005])//新大陆+京东刷卡
                    ->select('refund_amount');


                //银联二维码
                $unqr_order_data = $obj5->whereIn('store_id', $store_ids)
                    ->where($where)
                    ->whereIn('pay_status', [1, 6, 3])//成功+退款
                    ->whereNotIn('ways_type', [6005, 8005])//去除新大陆+京东刷卡
                    ->where('ways_source', 'unionpay')
                    ->select('total_amount', 'refund_amount', 'receipt_amount', 'fee_amount', 'mdiscount_amount');


                $unqr_refund_obj = RefundOrder::whereIn('store_id', $store_ids)
                    ->where($where)
                    ->where('ways_source', 'unionpay')
                    ->whereNotIn('type', [6005, 8005])//去除新大陆+京东刷卡
                    ->select('refund_amount');


            }

            //总的
            $total_amount = $order_data->sum('total_amount');//交易金额
            $refund_amount = $refund_obj->sum('refund_amount');//退款金额
            $fee_amount = $order_data->sum('fee_amount');//结算服务费/手续费
            $mdiscount_amount = '0';//$order_data->sum('mdiscount_amount');//商家优惠金额
            $get_amount = $total_amount - $refund_amount - $mdiscount_amount;//商家实收，交易金额-退款金额
            $receipt_amount = $get_amount - $fee_amount;//实际净额，实收-手续费
            $e_order = '' . $e_order . '';
            $total_count = '' . count($order_data->get()) . '';
            $refund_count = count($refund_obj->get());

            //支付宝
            $alipay_total_amount = $alipay_order_data->sum('total_amount');//交易金额
            $alipay_refund_amount = $alipay_refund_obj->sum('refund_amount');//退款金额
            $alipay_fee_amount = $alipay_order_data->sum('fee_amount');//结算服务费/手续费
            $alipay_mdiscount_amount = '0';// $alipay_order_data->sum('mdiscount_amount');//商家优惠金额
            $alipay_get_amount = $alipay_total_amount - $alipay_refund_amount - $alipay_mdiscount_amount;//商家实收，交易金额-退款金额
            $alipay_receipt_amount = $alipay_get_amount - $alipay_fee_amount;//实际净额，实收-手续费
            $alipay_total_count = '' . count($alipay_order_data->get()) . '';
            $alipay_refund_count = count($alipay_refund_obj->get());


            //微信
            $weixin_total_amount = $weixin_order_data->sum('total_amount');//交易金额
            $weixin_refund_amount = $weixin_refund_obj->sum('refund_amount');//退款金额
            $weixin_fee_amount = $weixin_order_data->sum('fee_amount');//结算服务费/手续费
            $weixin_mdiscount_amount = '0';// $weixin_order_data->sum('mdiscount_amount');//商家优惠金额
            $weixin_get_amount = $weixin_total_amount - $weixin_refund_amount - $weixin_mdiscount_amount;//商家实收，交易金额-退款金额
            $weixin_receipt_amount = $weixin_get_amount - $weixin_fee_amount;//实际净额，实收-手续费
            $weixin_total_count = '' . count($weixin_order_data->get()) . '';
            $weixin_refund_count = count($weixin_refund_obj->get());


            //京东
            $jd_total_amount = $jd_order_data->sum('total_amount');//交易金额
            $jd_refund_amount = $jd_refund_obj->sum('refund_amount');//退款金额
            $jd_fee_amount = $jd_order_data->sum('fee_amount');//结算服务费/手续费
            $jd_mdiscount_amount = '0';// $jd_order_data->sum('mdiscount_amount');//商家优惠金额
            $jd_get_amount = $jd_total_amount - $jd_refund_amount - $jd_mdiscount_amount;//商家实收，交易金额-退款金额
            $jd_receipt_amount = $jd_get_amount - $jd_fee_amount;//实际净额，实收-手续费
            $jd_total_count = '' . count($jd_order_data->get()) . '';
            $jd_refund_count = count($jd_refund_obj->get());

            //银联刷卡
            $un_total_amount = $un_order_data->sum('total_amount');//交易金额
            $un_refund_amount = $un_refund_obj->sum('refund_amount');//退款金额
            $un_fee_amount = $un_order_data->sum('fee_amount');//结算服务费/手续费
            $un_mdiscount_amount = '0';//$un_order_data->sum('mdiscount_amount');//商家优惠金额
            $un_get_amount = $un_total_amount - $un_refund_amount - $un_mdiscount_amount;//商家实收，交易金额-退款金额
            $un_receipt_amount = $un_get_amount - $un_fee_amount;//实际净额，实收-手续费
            $un_total_count = '' . count($un_order_data->get()) . '';
            $un_refund_count = count($un_refund_obj->get());

            //银联扫码
            $unqr_total_amount = $unqr_order_data->sum('total_amount');//交易金额
            $unqr_refund_amount = $unqr_refund_obj->sum('refund_amount');//退款金额
            $unqr_fee_amount = $unqr_order_data->sum('fee_amount');//结算服务费/手续费
            $unqr_mdiscount_amount = '0';//$unqr_order_data->sum('mdiscount_amount');//商家优惠金额
            $unqr_get_amount = $unqr_total_amount - $unqr_refund_amount - $unqr_mdiscount_amount;//商家实收，交易金额-退款金额
            $unqr_receipt_amount = $unqr_get_amount - $unqr_fee_amount;//实际净额，实收-手续费
            $unqr_total_count = '' . count($unqr_order_data->get()) . '';
            $unqr_refund_count = count($unqr_refund_obj->get());


            $data = [
                'total_amount' => number_format($total_amount, 2, '.', ''),//交易金额
                'total_count' => '' . $total_count . '',//交易笔数
                'refund_count' => '' . $refund_count . '',//退款金额
                'get_amount' => number_format($get_amount, 2, '.', ''),//商家实收，交易金额-退款金额
                'refund_amount' => number_format($refund_amount, 2, '.', ''),//退款金额
                'receipt_amount' => number_format($receipt_amount, 2, '.', ''),//实际净额，实收-手续费
                'fee_amount' => number_format($fee_amount, 2, '.', ''),//结算服务费/手续费
                'mdiscount_amount' => number_format($mdiscount_amount, 2, '.', ''),

                'alipay_total_amount' => number_format($alipay_total_amount, 2, '.', ''),//交易金额
                'alipay_total_count' => '' . $alipay_total_count . '',//交易笔数
                'alipay_refund_count' => '' . $alipay_refund_count . '',//退款金额
                'alipay_get_amount' => number_format($alipay_get_amount, 2, '.', ''),//商家实收，交易金额-退款金额
                'alipay_refund_amount' => number_format($alipay_refund_amount, 2, '.', ''),//退款金额
                'alipay_receipt_amount' => number_format($alipay_receipt_amount, 2, '.', ''),//实际净额，实收-手续费
                'alipay_fee_amount' => number_format($alipay_fee_amount, 2, '.', ''),//结算服务费/手续费
                'alipay_mdiscount_amount' => number_format($alipay_mdiscount_amount, 2, '.', ''),

                'weixin_total_amount' => number_format($weixin_total_amount, 2, '.', ''),//交易金额
                'weixin_total_count' => '' . $weixin_total_count . '',//交易笔数
                'weixin_refund_count' => '' . $weixin_refund_count . '',//退款金额
                'weixin_get_amount' => number_format($weixin_get_amount, 2, '.', ''),//商家实收，交易金额-退款金额
                'weixin_refund_amount' => number_format($weixin_refund_amount, 2, '.', ''),//退款金额
                'weixin_receipt_amount' => number_format($weixin_receipt_amount, 2, '.', ''),//实际净额，实收-手续费
                'weixin_fee_amount' => number_format($weixin_fee_amount, 2, '.', ''),//结算服务费/手续费
                'weixin_mdiscount_amount' => number_format($weixin_mdiscount_amount, 2, '.', ''),

                'jd_total_amount' => number_format($jd_total_amount, 2, '.', ''),//交易金额
                'jd_total_count' => '' . $jd_total_count . '',//交易笔数
                'jd_refund_count' => '' . $jd_refund_count . '',//退款金额
                'jd_get_amount' => number_format($jd_get_amount, 2, '.', ''),//商家实收，交易金额-退款金额
                'jd_refund_amount' => number_format($jd_refund_amount, 2, '.', ''),//退款金额
                'jd_receipt_amount' => number_format($jd_receipt_amount, 2, '.', ''),//实际净额，实收-手续费
                'jd_fee_amount' => number_format($jd_fee_amount, 2, '.', ''),//结算服务费/手续费
                'jd_mdiscount_amount' => number_format($jd_mdiscount_amount, 2, '.', ''),

                'un_total_amount' => number_format($un_total_amount, 2, '.', ''),//交易金额
                'un_total_count' => '' . $un_total_count . '',//交易笔数
                'un_refund_count' => '' . $un_refund_count . '',//退款金额
                'un_get_amount' => number_format($un_get_amount, 2, '.', ''),//商家实收，交易金额-退款金额
                'un_refund_amount' => number_format($un_refund_amount, 2, '.', ''),//退款金额
                'un_receipt_amount' => number_format($un_receipt_amount, 2, '.', ''),//实际净额，实收-手续费
                'un_fee_amount' => number_format($un_fee_amount, 2, '.', ''),//结算服务费/手续费
                'un_mdiscount_amount' => number_format($un_mdiscount_amount, 2, '.', ''),

                'unqr_total_amount' => number_format($unqr_total_amount, 2, '.', ''),//交易金额
                'unqr_total_count' => '' . $unqr_total_count . '',//交易笔数
                'unqr_refund_count' => '' . $unqr_refund_count . '',//退款金额
                'unqr_get_amount' => number_format($unqr_get_amount, 2, '.', ''),//商家实收，交易金额-退款金额
                'unqr_refund_amount' => number_format($unqr_refund_amount, 2, '.', ''),//退款金额
                'unqr_receipt_amount' => number_format($unqr_receipt_amount, 2, '.', ''),//实际净额，实收-手续费
                'unqr_fee_amount' => number_format($unqr_fee_amount, 2, '.', ''),//结算服务费/手续费
                'unqr_mdiscount_amount' => number_format($unqr_mdiscount_amount, 2, '.', ''),

            ];

            return ['status' => 1, 'message' => '数据返回成功', 'data' => $data];

        } catch (\Exception $exception) {
            return ['status' => 2, 'message' => $exception->getMessage()];

        }
    }


    public function order_list(Request $request)
    {

        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);


            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            $device_id = $data['device_id'];
            $device_type = $data['device_type'];


            $store_id = isset($data['store_id']) ? $data['store_id'] : "";
            $merchant_id = isset($data['merchant_id']) ? $data['merchant_id'] : "";
            $time_start_s = date('Y-m-d 00:00:00', time());
            $time_start_e = date('Y-m-d 23:59:59', time());

            $time_start = $time_start_s;
            $time_end = $time_start_e;


            //有门店ID
            if ($store_id) {
                $merchant_name = '';
                $config_id = '';

            } else {
                $Device = Device::where('device_type', $device_type)
                    ->where('device_no', $device_id)
                    ->first();

                if (!$Device) {
                    $err = [
                        'return_code' => 'FALL',
                        'return_msg' => '设备未绑定',
                    ];
                    return $this->return_data($err);
                }

                $merchant_id = $Device->merchant_id;
                $merchant_name = $Device->merchant_name;
                $store_id = $Device->store_id;
                $store_name = $Device->store_name;
                $config_id = $Device->config_id;
            }


            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
                'store_id' => $store_id,
            ];
            $where = [];
            if ($merchant_id) {
                $where[] = ['merchant_id', '=', $merchant_id];
            }

            if ($store_id) {
                $where[] = ['store_id', '=', $store_id];
            }


            //跨天操作
            $time_start_db = date('Ymd', strtotime($time_start));
            $time_end_db = date('Ymd', strtotime($time_end));
            $is_ct_time = 0;
            if ($time_start_db != $time_end_db) {
                $is_ct_time = 1;
            }

            $day = date('Ymd', strtotime($time_end));
            $table = 'orders_' . $day;

            if (env('DB_D1_HOST')) {
                //有没有跨天
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                        $obj = DB::connection("mysql_d1")->table('order_items');

                    } else {
                        $obj = DB::connection("mysql_d1")->table('orders');
                    }
                } else {

                    if (Schema::hasTable($table)) {
                        $obj = DB::connection("mysql_d1")->table($table);

                    } else {
                        if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                            $obj = DB::connection("mysql_d1")->table('order_items');

                        } else {
                            $obj = DB::connection("mysql_d1")->table('orders');
                        }
                    }
                }
            } else {
                if ($is_ct_time) {
                    if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                        $obj = DB::table('order_items');
                    } else {
                        $obj = DB::table('orders');
                    }
                } else {

                    if (Schema::hasTable($table)) {
                        $obj = DB::table($table);

                    } else {
                        if (Schema::hasTable('order_items') && $time_start >= "2019-12-21 00:00:00") {
                            $obj = DB::table('order_items');

                        } else {
                            $obj = DB::table('orders');
                        }
                    }
                }
            }


            $re_data['data'] = $obj->where($where)
                ->where('pay_status', 1)
                ->select('total_amount', 'ways_source_desc', 'pay_time')
                ->orderBy('created_at', 'desc')
                ->take(5)
                ->get();


            return $this->return_data($re_data);


        } catch (\Exception $exception) {

            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine(),];
            return $this->return_data($err);
        }


    }


    //查商户接口
    public function getstore_name(Request $request)
    {

        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);


            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            $device_id = $data['device_id'];
            $device_type = $data['device_type'];

            $Device = Device::where('device_type', $device_type)
                ->where('device_no', $device_id)
                ->first();

            if (!$Device) {
                $err = [
                    'return_code' => 'FALL',
                    'return_msg' => '设备不存在',
                ];
                return $this->return_data($err);
            }

            $store_name = $Device->store_name;
            $merchant_name = $Device->merchant_name;
            $merchant_id = $Device->store_id;
            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
            ];


            $re_data['store_name'] = $store_name;
            $re_data['merchant_name'] = $merchant_name;
            $re_data['merchant_id'] = $merchant_id;

            return $this->return_data($re_data);


        } catch (\Exception $exception) {

            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine(),];
            return $this->return_data($err);
        }

    }

    //订单监控
    public function check_order(Request $request)
    {
        try {
            $day = date('Ymd', time());
            $table = 'orders_' . $day;
            $start_time = time() - 5;
            $end_time = time() - 60;
            $end_time = date('Y-m-d H:i:s', $end_time);
            $start_time = date('Y-m-d H:i:s', $start_time);
            $where[] = ['created_at', '>=', $end_time];
            $where[] = ['created_at', '<', $start_time];
            $where[] = ['pay_status', '=', 2];
            if (Schema::hasTable($table)) {
                $order = DB::table($table)->where($where)->select('out_trade_no', 'store_id')->get()
                    ->toArray();

            } else {
                $order = Order::where($where)->select('out_trade_no', 'store_id')->get()
                    ->toArray();
            }

            foreach ($order as $key => $value) {
                $a = array('a', '_', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
                $b = str_ireplace($a, "", $value->out_trade_no);
                $day = substr($b, 0, 8);
                $table = 'orders_' . $day;


                if (Schema::hasTable($table)) {
                    $order = DB::table($table)->where('out_trade_no', $value->out_trade_no)
                        ->where('store_id', $value->store_id)
                        ->first();
                } else {
                    $order = Order::where('out_trade_no', $value->out_trade_no)
                        ->where('store_id', $value->store_id)
                        ->first();
                }

                if (!$order) {
                    return json_encode(['status' => 2, 'message' => "订单号不存在"]);
                }
                if ($order->pay_status == 6) {
                    return json_encode(['status' => 2, 'message' => "退款订单无法同步状态"]);
                }

                $data = [
                    'out_trade_no' => $order->out_trade_no,
                    'store_id' => $order->store_id,
                    'ways_type' => $order->ways_type,
                    'config_id' => $order->config_id,
                    'table' => $table,
                ];

                $obj = new OrderController();
                $return = $obj->order_foreach_public($data);
                return $return;
            }
        } catch (\Exception $exception) {
            return json_encode(['status' => 2, 'message' => $exception->getLine()]);
        }
    }

    public function get_refund_no(Request $request)
    {
        try {
            //获取请求参数
            $data = $request->getContent();
            $data = json_decode($data, true);


            //验证签名
            $check = $this->check_md5($data);
            if ($check['return_code'] == 'FALL') {
                return $this->return_data($check);
            }

            $trade_no = $data['trade_no'];
            $a = array('a', '_', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
            $b = str_ireplace($a, "", $out_trade_no);
            $day = substr($b, 0, 8);
            $table = 'orders_' . $day;


            if (Schema::hasTable($table)) {
                $order = DB::table($table)->where('trade_no', $trade_no)
                    ->first();
            } else {
                $order = Order::where('trade_no', $trade_no)
                    ->first();
            }
            //公共返回参数
            $re_data = [
                'return_code' => 'SUCCESS',
                'return_msg' => '返回成功',
            ];


            $re_data['out_trade_no'] = $order->out_trade_no;

            return $this->return_data($re_data);


        } catch (\Exception $exception) {

            $err = [
                'return_code' => 'FALL',
                'return_msg' => $exception->getMessage() . $exception->getLine(),];
            return $this->return_data($err);
        }
    }
}